I 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.
Yes. 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
Very 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.