首页 > 解决方案 > 如何在使用函数时加快处理速度

问题描述

我写了 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

解决方案


有很多方法可以优化你的 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

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

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


推荐阅读