I need to round lots of UNIX timestamps down to their respective minutes (expressed as timestamp again).
Out of pure curiosity I timed two methods:
%timeit (127/60)*60
10000000 loops, best of 3: 76.2 ns per loop
%timeit 127 - 127%60
10000000 loops, best of 3: 34.1 ns per loop
I ran this several times and second method is consistently around twice as fast as first one. Why is the difference so big?
>>> import dis
>>> method1 = lambda: (127 / 60) * 60
>>> method2 = lambda: 127 - 127 % 60
>>> dis.dis(method1)
1 0 LOAD_CONST 1 (127)
3 LOAD_CONST 2 (60)
6 BINARY_DIVIDE
7 LOAD_CONST 2 (60)
10 BINARY_MULTIPLY
11 RETURN_VALUE
>>> dis.dis(method2)
1 0 LOAD_CONST 1 (127)
3 LOAD_CONST 3 (7)
6 BINARY_SUBTRACT
7 RETURN_VALUE
In the second case, the modulo operation is simply optimized away.
Division is heavy operation relative to other operations (+
, -
, *
, %
) according to following timeit results:
In [9]: timeit 127 + 12
100000000 loops, best of 3: 14.8 ns per loop
In [10]: timeit 127 - 12
100000000 loops, best of 3: 14.8 ns per loop
In [11]: timeit 127 * 12
100000000 loops, best of 3: 14.9 ns per loop
In [12]: timeit 127 / 12
10000000 loops, best of 3: 40 ns per loop
In [13]: timeit 127 % 12
100000000 loops, best of 3: 14.7 ns per loop
UPDATE
I was wrong. Using varaible, shows different results as Tim Peters commented.
In [1]: a, b = 127, 12
In [2]: timeit a + b
10000000 loops, best of 3: 37.6 ns per loop
In [3]: timeit a - b
10000000 loops, best of 3: 37.9 ns per loop
In [4]: timeit a * b
10000000 loops, best of 3: 52.7 ns per loop
In [5]: timeit a / b
10000000 loops, best of 3: 54 ns per loop
In [6]: timeit a % b
10000000 loops, best of 3: 56.5 ns per loop
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