python - Why is `if` so much faster when checked before a statement than after a statement? -


here's example of 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 computer, regardless of setup (x=5 vs x=15, no difference)


if use shorter code, 1 first decreases x -= 10 , checks if x < 0, 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 initial value of x 5 or 15.


i understand slower when x < 10 since we'd first call x -= 10 , set x = 0 instead of setting x once.

the thing is, 99% of time x's initial value in program set number higher 10, thought i'd use shorter version since of time should see no difference in performance.

however, there's huge difference in performance when x > 10, why's this?

your premise wrong. setup gets run once entire timeit. if make sure x stays above 10 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 

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -