python 调用函数 开销_Python函数调用非常慢
這主要是為了確保我的方法是正確的,但我的基本問題是,如果我需要訪問函數(shù),那么檢查函數(shù)外部是否值得.我知道,我知道,過早優(yōu)化,但在很多情況下,它在函數(shù)調(diào)用中放置一個if語句以確定是否需要運行其余代碼,或者將它放在函數(shù)調(diào)用之前.換句話說,它不會以任何方式做到這一點.現(xiàn)在,所有的檢查都在兩者之間混合,我想讓它變得更加美觀和標(biāo)準(zhǔn)化.
我問的主要原因是因為我看到的其他答案主要是參考timeit,但這給了我負數(shù),所以我切換到這個:
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)
對我來說,顯示不調(diào)用該函數(shù)是.31秒,并且調(diào)用它需要1.52秒,這幾乎慢了5倍.但就像我說的那樣,我得到了帶有timeit的負數(shù),所以我想確保它實際上很慢.
另外,從我收集的內(nèi)容來看,函數(shù)調(diào)用的原因是如此緩慢是因為python需要查找以確保函數(shù)在運行之前仍然存在或其他什么?是不是有任何方法只是告訴它喜歡…假設(shè)一切仍然存在,以便它不必做不必要的工作(顯然)減慢它5倍?
總結(jié)
以上是生活随笔為你收集整理的python 调用函数 开销_Python函数调用非常慢的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1025 反转链表 (25分)
- 下一篇: 【笔记】Python算法教程(1)