Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Surprising timeit result

1 view
Skip to first unread message

John O'Hagan

unread,
Oct 27, 2009, 12:36:12 AM10/27/09
to pytho...@python.org
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

Paul Rubin

unread,
Oct 27, 2009, 12:47:02 AM10/27/09
to
"John O'Hagan" <rese...@johnohagan.com> writes:
> 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.

John O'Hagan

unread,
Oct 27, 2009, 1:31:53 AM10/27/09
to pytho...@python.org

Of course:

Timer('d1 = {"a":0}; d2 = {"a":1}\nif d1 != d2: d1.update(d2)').timeit()
1.9810600280761719

Timer('d1 = {"a":0}; d2 = {"a":1}\nd1.update(d2)').timeit()
1.7072379589080811

as expected. I wasn't quite clear about how Timer() worked, is my excuse!

Thanks,

John

Steven D'Aprano

unread,
Oct 27, 2009, 2:18:36 AM10/27/09
to

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.


--
Steven

0 new messages