将字符串转换为int太慢了

Jam*_*igo 8 python performance python-3.x

我有一个程序,每行读取3个字符串50000.然后做其他事情.读取文件并转换为整数的部分占总运行时间的80%.

我的代码段如下:

import time
file = open ('E:/temp/edges_big.txt').readlines()
start_time = time.time()
for line in file[1:]:
    label1, label2, edge = line.strip().split()
    # label1 = int(label1); label2 = int(label2); edge = float(edge)
    # Rest of the loop deleted
print ('processing file took ', time.time() - start_time, "seconds")
Run Code Online (Sandbox Code Playgroud)

以上大约需要0.84秒.现在,当我取消注释该行

label1 = int(label1);label2 = int(label2);edge = float(edge)
Run Code Online (Sandbox Code Playgroud)

运行时间上升到大约3.42秒.

输入文件的格式为:str1 str2 str3每行

功能int()float()那个慢吗?我怎么能优化这个?

Tim*_*ker 1

我根本无法重现这个。

我生成了一个 50000 行的文件,每行包含三个随机数(两个整数,一个浮点数),用空格分隔。

然后我在该文件上运行你的脚本。原始脚本在我用了三年的 PC 上只需 0.05 秒即可完成,而带有未注释行的脚本则需要 0.15 秒才能完成。当然,字符串到 int/float 的转换需要更长的时间,但肯定不会达到几秒钟的程度。除非您的目标机器是运行嵌入式 Windows CE 的烤面包机。