Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is no difference in the generated bytecode, because the compiler does its job well and optimizes away the constant arithmetic expression. That means your test results are just a coincidence (try timing the functions in a different order!).</p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(test1) 2 0 SETUP_LOOP 30 (to 33) 3 LOAD_GLOBAL 0 (xrange) 6 LOAD_GLOBAL 1 (AMOUNT) 9 CALL_FUNCTION 1 12 GET_ITER &gt;&gt; 13 FOR_ITER 16 (to 32) 16 STORE_FAST 0 (i) 3 19 LOAD_FAST 0 (i) 22 LOAD_CONST 1 (65536) 25 BINARY_MODULO 26 STORE_FAST 1 (value) 29 JUMP_ABSOLUTE 13 &gt;&gt; 32 POP_BLOCK 4 &gt;&gt; 33 LOAD_CONST 0 (None) 36 RETURN_VALUE &gt;&gt;&gt; dis.dis(test5) 2 0 SETUP_LOOP 30 (to 33) 3 LOAD_GLOBAL 0 (xrange) 6 LOAD_GLOBAL 1 (AMOUNT) 9 CALL_FUNCTION 1 12 GET_ITER &gt;&gt; 13 FOR_ITER 16 (to 32) 16 STORE_FAST 0 (i) 3 19 LOAD_FAST 0 (i) 22 LOAD_CONST 3 (65536) 25 BINARY_MODULO 26 STORE_FAST 1 (value) 29 JUMP_ABSOLUTE 13 &gt;&gt; 32 POP_BLOCK 4 &gt;&gt; 33 LOAD_CONST 0 (None) 36 RETURN_VALUE </code></pre> <p>(well actually there is a difference: The number is stored at different offsets in the constant table. I can't imagine this causing any difference, though).</p> <p>For completeness, here's a proper test that uses the <code>timeit</code> module:</p> <pre><code>import timeit setup = "i = 1337" best1 = best2 = float("inf") for _ in range(5000): best1 = min(best1, timeit.timeit("i % 65536", setup=setup, number=10000)) for _ in range(5000): best2 = min(best2, timeit.timeit("i % (2**16)", setup=setup, number=10000)) print best1 print best2 </code></pre> <p>Note that I am measuring the <em>minimum</em> time needed, rather than the average. If it takes longer for some reason, this just means that it was interrupted more often (because the code doesn't depend on anything but the power of your CPU).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload