int()
进行转换非常缓慢。为什么?更重要的是:如何使它更快?因此,问题是:在Python中将字符串转换为整数的最快方法是什么?
我真正考虑的是一些半隐藏的Python功能,可以(滥用)用于此目的,类似于Guido在他的{{link1:“Optimization Anecdote”}}中使用
array.array
。示例数据(制表符展开为空格)
38262904 "pfv" 2002-11-15T00:37:20+00:00
12311231 "tnealzref" 2008-01-21T20:46:51+00:00
26783384 "hayb" 2004-02-14T20:43:45+00:00
812874 "qevzasdfvnp" 2005-01-11T00:29:46+00:00
22312733 "bdumtddyasb" 2009-01-17T20:41:04+00:00
这里读取数据所需的时间并不重要,处理数据才是瓶颈。
微基准测试
以下所有语言都是解释型语言。主机运行64位Linux。
Python 2.6.2与IPython 0.9.1,每秒约214k次转换(100%):
In [1]: strings = map(str, range(int(1e7)))
In [2]: %timeit map(int, strings);
10 loops, best of 3: 4.68 s per loop
REBOL 3.0 版本 2.100.76.4.2, ~231kcps (108%):
>> strings: array n: to-integer 1e7 repeat i n [poke strings i mold (i - 1)]
== "9999999"
>> delta-time [map str strings [to integer! str]]
== 0:00:04.328675
REBOL 2.7.6.4.2 (2008年3月15日),~523kcps(261%):
正如John在评论中指出的那样,此版本不会构建转换后整数的列表,因此给出的速度比是相对于Python运行for str in strings: int(str)
的4.99秒。
>> delta-time: func [c /local t] [t: now/time/precise do c now/time/precise - t]
>> strings: array n: to-integer 1e7 repeat i n [poke strings i mold (i - 1)]
== "9999999"
>> delta-time [foreach str strings [to integer! str]]
== 0:00:01.913193
KDB+ 2.6t 2009.04.15,~2016kcps(944%):
q)strings:string til "i"$1e7
q)\t "I"$strings
496
numpy.fromfile
来读取“十亿个正整数”(顺便问一下,“十亿”是什么意思(在美国是10的9次方,在英国可能是10的12次方)? - jfs