5 ms·
Unless you can prove that one method is significantly faster or the other structurally dangerous, it is just a matter of coding style and opinion. Agree to disa
by SeanDav 10y ago
Unless you can prove that one method is significantly faster or the other structurally dangerous, it is just a matter of coding style and opinion. Agree to disagree, or let the lint tool be the referee.
- gvb 10y ago$ python -m timeit 'float(5)' 10000000 loops, best of 3: 0.0776 usec per loop $ python -m timeit '5.0' 100000000 loops, best of 3: 0.00719 usec per loop
- jrs235 10y agoDid you have a typo? Or did you mean to only loop ten million times in the first case and 100 million in the second?
- gvb 10y agoI did the lazy approach and let timeit pick the count. Specifying the number of loops doesn't change the result: $ python -m timeit -n 10000000 'float(5)' 10000000 loops, best of 3: 0.0771 usec per loop $ python -m timeit -n 10000000 '5.0' 10000000 loops, best of 3: 0.00717 usec per loop [timeit] provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times. See also Tim Peters’ introduction to the “Algorithms” chapter in the Python Cookbook, published by O’Reilly. Ref: https://docs.python.org/2/library/timeit.html https://docs.python.org/2/library/timeit.html
- deleted 10y ago[deleted]
- Waterluvian 10y agoAm I reading that right: on average it's 10x faster to use a float literal?
- gvb 10y agoYes. The difference is the Python compiler is not optimizing out the float() conversion, so every time it creates the value 5.0 it is calling the float() conversion on the literal "5". Different machine, so the timings are different from above, but here are some permutations: Float literal: $ python -m timeit '5.0' 100000000 loops, best of 3: 0.0152 usec per loop Integer literal coerced to a float: $ python -m timeit 'float(5)' 10000000 loops, best of 3: 0.146 usec per loop Float literal coerced to a float: $ python -m timeit 'float(5.0)' 10000000 loops, best of 3: 0.143 usec per loop Integer literal: $ python -m timeit '5' 100000000 loops, best of 3: 0.0152 usec per loop Float literal coerced to an integer: $ python -m timeit 'int(5.0)' 10000000 loops, best of 3: 0.155 usec per loop Integer literal coerced to an integer: $ python -m timeit 'int(5)' 10000000 loops, best of 3: 0.14 usec per loop
- Waterluvian 10y agoVery cool thanks. So something like PyPy would probably very quickly optimize it, since it has a deterministic result. I think I'm going to experiment with that one.