简体   繁体   English

为什么将float转换为String并使用额外的拆分比转换为int更快?

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

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. 回答一个关于如何删除数字的浮点部分的问题(从100.25中删除.25),一个用户回答说int(float_num)是删除浮点部分的好方法。 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] . 这是我的答案: str(float_num).split('.')[0] Longer and uglier, this approach seems worse than just converting to int. 更长和更丑,这种方法似乎比转换为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? 也许拥有核心i7计算机会影响结果? Am I doing something wrong? 难道我做错了什么?

EDIT: The final answer's type doesn't need to be an int. 编辑:最终答案的类型不需要是一个int。 The point is just analyze why removing the float part is faster with the str method (in my case) 关键是要分析为什么使用str方法(在我的例子中)移除浮动部分更快

基准

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. 这是因为在str情况下你没有对转换进行基准测试,因为你没有将它们作为要执行的字符串。 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). 相反,Python解释器将在将结果(即“100”)提供给timeit之前执行“转换”,这将很乐意“执行”该语句(基本上什么都不做)。

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: 参考我的评论 - 类型转换为int是时间的流逝:

>>>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. 我相信一个简单的字符串操作比类型转换更快,即使它只是浮点到int你仍然将它作为一个新类型。

The String manipulation however is just chopping off part of what it already has, no complexity or maths involved. 然而,字符串操作只是削减它已有的部分内容,不涉及复杂性或数学。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM