这主要是为了确保我的方法是正确的,但我的基本问题是,如果我需要访问函数,那么检查函数外部是否值得.我知道,我知道,过早优化,但在很多情况下,它在函数调用中放置一个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 :1()
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 :1()
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)
对我来说,显示不调用该函数是.31秒,并且调用它需要1.52秒,这几乎慢了5倍.但就像我说的那样,我得到了带有timeit的负数,所以我想确保它实际上很慢.
另外,从我收集的内容来看,函数调用的原因是如此缓慢是因为python需要查找以确保函数在运行之前仍然存在或其他什么?是不是有任何方法只是告诉它喜欢…假设一切仍然存在,以便它不必做不必要的工作(显然)减慢它5倍?