3 ms·
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() conver
by gvb 10y ago
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
- 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.