Why is converting a float to String with additional split faster than just converting to int?

StackOverflow https://stackoverflow.com/questions/22623859

  •  20-06-2023
  •  | 
  •  

سؤال

Answering a question about how to remove the float part of a number (remove .25 from 100.25), one user answered that int(float_num) was a good way to remove it's float part. I came across a way using strings that I thought was obviously worse than that, but I thought it was interesting to consider it. This was my answer: str(float_num).split('.')[0]. Longer and uglier, this approach seems worse than just converting to int.

Then, could anyone explain me why the benchmarks I tried, gave better results to the longer method than to the simpler? Maybe having a core i7 computer affects the results? Am I doing something wrong?

EDIT: The final answer's type doesn't need to be an int. The point is just analyze why removing the float part is faster with the str method (in my case)

benchmarks

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

I believe a simple string manipulation is faster than a type conversion, even if it is simply float to int you are still casting it as a new type.

The String manipulation however is just chopping off part of what it already has, no complexity or maths involved.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top