Surprising timeit result

J

John O'Hagan

I sometimes use timeit to see if it's better to check if something needs doing,
or to just do it anyway. This result was surprising:

setup = 'd1 = {"a":0, "b":0}; d2 = {"a":0, "b":1}'

Timer('d1.update(d2)', setup).timeit()
2.6499271392822266

Timer('if d1 != d2: d1.update(d2)', setup).timeit()
1.0235211849212646

In other words, in this case it's substantially quicker to check for something and
then proceed, than it is to just proceed! I'm curious about the explanation.

Regards,

John
 
P

Paul Rubin

John O'Hagan said:
Timer('d1.update(d2)', setup).timeit()
2.6499271392822266

Timer('if d1 != d2: d1.update(d2)', setup).timeit()
1.0235211849212646

In other words, in this case it's substantially quicker to check for
something and then proceed, than it is to just proceed! I'm curious
about the explanation.

Looks to me like in both versions, d2 is only initialized once, so
the d1.update in the second case only gets called on the first loop.
It's not so surprising that comparing d1 and d2 is faster than
actually updating d1.
 
S

Steven D'Aprano

I sometimes use timeit to see if it's better to check if something needs
doing, or to just do it anyway. This result was surprising:

setup = 'd1 = {"a":0, "b":0}; d2 = {"a":0, "b":1}'

Timer('d1.update(d2)', setup).timeit() 2.6499271392822266

Timer('if d1 != d2: d1.update(d2)', setup).timeit() 1.0235211849212646

In other words, in this case it's substantially quicker to check for
something and then proceed, than it is to just proceed! I'm curious
about the explanation.

The code snippet is executed inside a loop. The first snippet runs
d1.update(d2) one million times. The second snippet runs "if d1 != d2"
one million times, and d1.update(d2) once.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
arinsharma
Top