如何在使用函数时加快处理速度

  • 本文关键字:处理速度 函数 python
  • 更新时间 :
  • 英文 :


我写了 simplePrint.py

simplePrint.py

print(1)
print(2)
print(3)

而且,我写了 functionPrint.py。

functionPrint.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

反正这是我的猜测。你可以看到这里还有很多事情要做,这需要时间。(特别是,创建本地范围是很多指令(。

(你绝对应该仍然使用函数,因为没有它们,任何复杂的编程都会很快失控。减速带可以忽略不计。

做一个简单的谷歌搜索得到:

为了编写高效的Python cde,这里有5件重要的事情要记住...

  1. 了解基本数据结构。
  2. 减少内存占用。
  3. 使用内置函数和库。
  4. 将计算移出循环。
  5. 保持较小的代码库。

如果你想测试你的脚本,看看哪个运行得更快,你可以使用这个(摘自这篇文章(:
import time
start_time = time.time()
// Your main code here
print("--- %s seconds ---" % (time.time() - start_time))

最新更新