Python Forum

Full Version: which is faster?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
which is faster when arg1 is None?

code 1:
def fun1(arg1,arg2):
    if arg1 is None:
        return None
    . . .
code 2:
def fun1(arg1,arg2):
    if arg1 is None:
        return arg1
    . . .
are there any examples of timing python code in a script with timeit?
(Apr-17-2023, 04:53 PM)Skaperen Wrote: [ -> ]are there any examples of timing python code in a script with timeit?
Here is one, which tells you that func() executes in 0.05 microseconds. It does this by running func() one million times.
>>> def func():
...     pass
... 
>>> import timeit
>>> timeit.timeit("func()", setup="from __main__ import func")
0.05375158700189786
i'm getting about the same timing, plus or minus noise. i'll have to do the min() thing or look at the generated code (wondering how it loads that value). OTOH, if i can't tell the difference, then i guess it doesn't matter, even for a performance oriented person like me.

i wonder which is more pythonic, loading a literal or a variable that was tested as being the same.

i once coded in IBM mainframe assembly, long, long ago, i even wrote code to do a 16-bit x 16-bit multiply to get a 32-bit result that ran faster than the mainframe's own CPU instruction that did the same thing.
(Apr-17-2023, 11:31 PM)Skaperen Wrote: [ -> ]i wonder which is more pythonic,
return None is more explicit. No reflection is needed to understand what it does. I think it's better.