It is because in the str
case you're not benchmarking the conversion, because you didn't put them as a string to be executed. Rather, the Python interpreter will execute the "conversion" before giving the result (which is "100") into timeit
, which will happily "execute" the statement (which is basically doing nothing).
Putting the statement to be run in quotes, increases the time by order of magnitude, showing the actual running time:
>>>timeit.timeit('str(100.25).split(".")[0]', number = 100000)
0.0971575294301
>>>timeit.timeit(str(100.25).split(".")[0], number = 100000)
0.00131594451899
Referring to my comment - the type conversion to int is where the time is going:
>>>timeit.timeit('int(str(100.25).split(".")[0])', number = 100000)
0.14871997597698083
>>> timeit.timeit(str(100.25).split(".")[0], number = 100000)
0.0013893059552003706
>>> timeit.timeit('int(100.25)', number = 100000)
0.019588643801725425
And as your number gets longer, the string method will get slower quicker than the integer method. They grow at different rates.