python 调用函数 开销_Python函数调用非常慢

这主要是为了确保我的方法是正确的,但我的基本问题是,如果我需要访问函数,那么检查函数外部是否值得.我知道,我知道,过早优化,但在很多情况下,它在函数调用中放置一个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倍?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值