Here's an example of what I mean:
s = """
if x > 10:
x -= 10
else:
x = 0
"""
import timeit
print(timeit.timeit(s, setup="x=5", number=99999999))
Outputs approximately 3 seconds on my computer, regardless of the setup (x=5
vs x=15
, no difference)
If I were to use much shorter code, one that first decreases x -= 10
and only then checks if x < 0
, I will get much worse results:
s = """
x -= 10
if x < 0:
x = 0
"""
import timeit
print(timeit.timeit(s, setup="x=5", number=99999999))
It outputs around 6 seconds, again regardless whether the initial value of x
was 5
or 15
.
I understand that it would be slower when x < 10
since we'd first call x -= 10
and then set x = 0
instead of simply setting x
once.
The thing is, 99% of the time the x
's initial value in my program is set to a number much higher than 10, so I thought I'd use the shorter version since most of the time I should see no difference in performance.
However, there's a huge difference in performance even when x > 10
, why's this?
A switch statement *might* be faster than ifs. I say might because it depends on your use case and the compiler you're using. A switch uses jump tables under the hood so it's able to generate something like value -> function to call for every value in your range and figure out the code path using one lookup.
Why are Prepared Statements in JDBC faster than Statements? Explain? While executing statements using Statement object, especially insert statements, each time a query is executed the whole statement is compiled and executed again and again where, the only difference among these statements is the values of the statements.
Why is My Query Faster the Second Time it Runs? (Dear SQL DBA Episode 23) - littlekendra.com Why is My Query Faster the Second Time it Runs? (Dear SQL DBA Episode 23) It takes CPU time to figure out how to run a query. SQL Server uses memory to cache execution plans to save time the next time you run the query.
There is no such limitation to the IF statement loop. Admittedly, applications that require nesting more than three deep are few and far between—but this just contributed to my feeling that using the IF statement loop is better. However, I was not aware of one important advantage to using the WHILE statement loop.
Your premise is wrong. setup
only gets run once for the entire timeit
. If you make sure that x
stays above 10
then the symptoms disappear:
>>> s1 = """
... if x > 10:
... x -= 10
... else:
... x = 0
... """
>>> s2 = """
... x -= 10
... if x < 0:
... x = 0
... """
>>> import timeit
>>> print(timeit.timeit(s1, setup="x=1000000000", number=99999999))
8.934118068675566
>>> print(timeit.timeit(s2, setup="x=1000000000", number=99999999))
8.744505329313448
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With