python - 如何在使用函数时加快处理速度
问题描述
我写了 simplePrint.py
简单打印.py
print(1)
print(2)
print(3)
而且,我写了functionPrint.py。
函数打印.py
def printTestFunction(one,two,three):
print(one)
print(two)
print(three)
printTestFunction(1,2,3)
这可能很自然,但 functionPrint.py 较慢。
有没有办法在使用函数时加快处理速度?
速度比较方法如下
import timeit
class checkTime():
def __init__(self):
self.a = 0
self.b = 0
self.c = 0
def local(self):
print(1)
print(2)
print(3)
def self(self):
def printTestFunction(one,two,three):
print(one)
print(two)
print(three)
printTestFunction(1,2,3)
def getTime(self):
def test1():
self.self()
self_elapsed_time = timeit.Timer(stmt=test1).repeat(number=10000)
def test2():
self.local()
local_elapsed_time = timeit.Timer(stmt=test2).repeat(number=10000)
print ("local_time:{0}".format(local_elapsed_time) + "[sec]")
print ("self_time:{0}".format(self_elapsed_time) + "[sec]")
checkTime = checkTime()
checkTime.getTime()
结果
local_time:[0.04716750000000003, 0.09638709999999995, 0.07357000000000002, 0.04696279999999997, 0.04360750000000002][sec]
self_time:[0.09702539999999998, 0.111617, 0.07951390000000003, 0.08777400000000002, 0.099128][sec]
解决方案
有很多方法可以优化你的 Python,但对于这么简单的事情,我不会担心。函数调用在人类时间里几乎是瞬间完成的。
大多数语言中的函数调用必须为参数创建新变量,创建本地范围,执行所有操作。所以:
def printTestFunction(one,two,three):
print(one)
print(two)
print(three)
printTestFunction(1,2,3)
运行这样的东西:
define function printTestFunction
call function with args (1, 2, 3)
create local scope
one=arg[0]
two=arg[1]
three=arg[2]
print(one)
print(two)
print(three)
return None
destroy local scope
garbage collect
无论如何,这是我的猜测。你可以看到这里还有很多事情要做,这需要时间。(特别是,创建一个本地范围是很多指令)。
(你绝对应该使用函数,因为没有它们,任何复杂的东西都会很快失控。减速可以忽略不计。)
推荐阅读
- java - 使用 multipart/form-data 或 multipart/mixed 获取 JSON 和文件时让 Spring 映射
- java - 尽可能快地发送数据包时,Rust 与 Java 中的不同网络行为
- google-bigquery - 从输入数组中查找包含最多项目的数组
- php - 仅当不为空或 null 时才输出数组的值
- android - Firebase 实时数据库:用户 ID 未显示在子项中
- python - 根据另外两个字典替换字典值列表
- javascript - Chrome 扩展程序:URL 权限不起作用
- powershell - 使用 Powershell 从一个文件夹中的多个 CSV 文件中删除前 15 行
- druid - 创建Druid schema时为什么需要在dimensionSpec中添加列
- heroku - 可以将敏感配置添加到 heroku.yml 文件并提交到 Heroku 的 GIT 存储库吗?