This is mostly to make sure my methodology is correct, but my basic question was is it worth it to check outside of a function if I need to access the function at all. I know, I know, premature optimization, but in many cases, its the difference between putting an if statement inside the function call to determine whether I need to run the rest of the code, or putting it before the function call. In other words, it takes no effort to do it one way or the other. Right now, all the checks are mixed between both, and I'd like the get it all nice and standardized.
The main reason I asked is because the other answers I saw mostly referenced timeit, but that gave me negative numbers, so I switched to this:
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')
and got this for output
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)
To me that shows that not calling the function is .31 seconds, and calling it takes 1.52 seconds, which is almost 5 times slower. But like I said, I got negative numbers with timeit, so I want to make sure its actually that slow.
Also from what I gather, the reason function calls are so slow is because python needs to look up to make sure the function still exists before it can run it or something? Isn't there any way to just tell it to like...assume that everything is still there so that it doesn't have to do unnecessary work that (apparently) slows it down 5x?