为什么 float() 比 int() 快? [英] Why is float() faster than int()?

查看:79
本文介绍了为什么 float() 比 int() 快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用一些代码进行实验并进行一些微基准测试,我刚刚发现在包含整数的字符串上使用 float 函数比在上使用 int 快 2 倍相同的字符串.

<预><代码>>>>python -m timeit int('1')1000000 个循环,最好的 3 个:每个循环 0.548 微秒>>>python -m timeit float('1')1000000 个循环,最好的 3 个:每个循环 0.273 微秒

在测试 int(float('1')) 时,它变得更奇怪,哪个运行时比裸 int('1') 短.

<预><代码>>>>python -m timeit int(float('1'))1000000 个循环,3 个最佳:每个循环 0.457 微秒

我在运行 cPython 2.7.6 的 Windows 7 和带有 cPython 2.7.6 的 Linux Mint 16 下测试了代码.

我必须补充一点,只有 Python 2 受到影响,Python 3 显示运行时之间的差异更小(不显着).

我知道我通过此类微基准测试获得的信息很容易被滥用,但我很好奇为什么函数的运行时会有如此大的差异.

我试图找到 intfloat 的实现,但在源代码中找不到.

解决方案

int 有很多基础.

*, 0*, 0x*, 0b*, 0o* 并且可以很长,确定基数等需要时间

如果设置了基数,可以节省很多时间

python -m timeit "int('1',10)"1000000 个循环,最好的 3 个:每个循环 0.252 微秒python -m timeit "int('1')"1000000 个循环,最好的 3 个:每个循环 0.594 微秒

正如@Martijn Pieters 提到的代码 Object/intobject.c(int_new)Object/floatobject.c(float_new)

Experimenting with some code and doing some microbenchmarks I just found out that using the float function on a string containing an integer number is a factor 2 faster than using int on the same string.

>>> python -m timeit int('1')
1000000 loops, best of 3: 0.548 usec per loop

>>> python -m timeit float('1')
1000000 loops, best of 3: 0.273 usec per loop

It gets even stranger when testing int(float('1')) which runtime is shorter than the bare int('1').

>>> python -m timeit int(float('1'))
1000000 loops, best of 3: 0.457 usec per loop

I tested the code under Windows 7 running cPython 2.7.6 and Linux Mint 16 with cPython 2.7.6.

I have to add that only Python 2 is affected, Python 3 shows a way smaller (not remarkable) difference between the runtimes.

I know that the information I get by such microbenchmarks are easy to misuse, but I'm curious why there is such a difference in the functions' runtime.

I tried to find the implementations of int and float but I can not find it in the sources.

解决方案

int has lots of bases.

*, 0*, 0x*, 0b*, 0o* and it can be long, it takes time to determine the base and other things

if the base is set, it saves a lot of time

python -m timeit "int('1',10)"       
1000000 loops, best of 3: 0.252 usec per loop

python -m timeit "int('1')"   
1000000 loops, best of 3: 0.594 usec per loop

as @Martijn Pieters metions the code the Object/intobject.c(int_new) and Object/floatobject.c(float_new)

这篇关于为什么 float() 比 int() 快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆