这主要是为了确保我的方法正确,但我的基本问题是,如果我需要访问函数,是否值得在函数外部检查。我知道,我知道,过早优化,但在许多情况下,这是放置if语句以确定是否需要运行其余代码的函数调用内部和函数调用前面之间的区别。换句话说,将其一种方式或另一种方式实现都不需要太多的工作。现在,所有的检查都混杂在两者之间,我想将它们全部标准化。
我提出这个问题的主要原因是因为我看到的其他答案大多都涉及timeit,但那给了我负数,所以我转而采用了这种方式:
import timeit
import cProfile
def aaaa(idd):
return idd
def main():
#start = timeit.timeit()
for i in range(9999999):
a = 5
#end = timeit.timeit()
#print("1", end - start)
def main2():
#start = timeit.timeit()
for i in range(9999999):
aaaa(5)
#end = timeit.timeit()
#print("2", end - start)
cProfile.run('main()', sort='cumulative')
cProfile.run('main2()', sort='cumulative')
并且得到了这个输出
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.310 0.310 {built-in method exec}
1 0.000 0.000 0.310 0.310 <string>:1(<module>)
1 0.310 0.310 0.310 0.310 test.py:7(main)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.044 2.044 {built-in method exec}
1 0.000 0.000 2.044 2.044 <string>:1(<module>)
1 1.522 1.522 2.044 2.044 test.py:14(main2)
9999999 0.521 0.000 0.521 0.000 test.py:4(aaaa)
对我来说,这表明不调用该函数需要0.31秒,而调用它需要1.52秒,几乎慢了5倍。但是正如我所说,使用timeit时我得到了负数,因此我想确保它实际上就是这么慢。
另外据我所知,函数调用之所以如此缓慢是因为Python需要查找以确保函数仍然存在,然后才能运行它或者做其他一些事情?难道没有办法告诉Python假设所有东西都还在,这样它就不必执行不必要的工作,从而提高速度(显然可以)?
timeit
函数得到负数的? - Martijn Pieterstimeit.timeit()
是测量执行一百万次无操作所需的时间。从timeit.timeit()
中减去timeit.timeit()
可能是负数。 - unutbu