Python Forum
which is faster? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: which is faster? (/thread-39812.html)



which is faster? - Skaperen - Apr-17-2023

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
    . . .



RE: which is faster? - Gribouillis - Apr-17-2023

timeit: measure execution time of small code snippets


RE: which is faster? - Skaperen - Apr-17-2023

are there any examples of timing python code in a script with timeit?


RE: which is faster? - Gribouillis - Apr-17-2023

(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



RE: which is faster? - Skaperen - Apr-17-2023

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.


RE: which is faster? - Gribouillis - Apr-18-2023

(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.