IronPython与CPython的文件读取和解析性能

2024-04-25 03:58:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在用python开发一个文件读取器,我希望在那里读取大约100MB的ascii文件。顶部有一堆标题信息,然后是制表符分隔的列。有些列包含非数字数据(我现在不关心)。我有一个matlab实现,它可以在不到1.5秒的时间内读取一个30MB的示例文件。我的python阅读器在CPython中大约需要2秒,而在IronPython中大约需要4秒。区别似乎在于字符串值被转换成浮点值的位置,但我无法在IronPython中使其更快。在

我在这里的最新迭代有以下循环来读取和解析这些行

#-Parse the actual data lines
istep = -1
while len(line) > 0:

    istep += 1
    #-Split the line and convert pasred values to floats
    timestep = line.split();            
    for ichan in numericChannels:                    
        data[ichan].append(float(timestep[ichan]))

    line = f.readline().strip()

numericChannels是一个整数列表,指定我要读取哪些频道。data是一个列表列表,其中is sub list是一列数据。在

性能上的差异似乎来自于浮点转换。我能在IronPython上做些什么来加速这个过程吗?我甚至试过一段时间读过这个文件然后用系统线程化任务.并行.ForEach构造来解析文件行。那根本没用。在

谢谢。在


Tags: 文件the数据标题列表datalineascii
3条回答

在我看来,像这样的事情可能会快一点。在

import operator
data=[]
istep = -1
columngetter=operator.itemgetter(*numericChannels)
while len(line) > 0:
    istep += 1
    #-Split the line and convert parsed values to floats
    timestep = line.split()
    data.append(map(float,columngetter(timestep)))
    line = f.readline().strip()

data=zip(*data)

看来IronPython只是在读取文本文件时比CPython慢。我在Python的几个版本中运行了这个片段(partest2.txt文件在一行中给出了200000个数字):

import sys
import timeit

tmr = timeit.Timer("with open(r'partest2.txt','r') as fid:fid.readlines()")
res = tmr.timeit(number=20)
print(res)

结果:

  • CPython 2.7:1.282
  • CPython 3.3:1.562
  • IronPython 2.6[.NET 2]:2.196
  • IronPython 2.7[.NET 4]:2.880

IronPython运行时发出以下警告(不确定它是否会影响任何内容):

< string>:1: RuntimeWarning: IronPython has no support for disabling the GC

当被读取的文件(partest2.txt)被改变,使它有相同的200000个数字在它自己的行中给出,这里是计时(完全不同)

  • CPython 2.7:4.04
  • CPython 3.3:7.61
  • IronPython 2.7[.NET 4]:20.22
  • IronPython 2.6[.NET 2]:21.46

哎呀!在

a)你说“区别在于字符串值被转换成浮动的地方”——你为什么这么认为?你对代码运行了探查器吗?在

b)如果你有记忆力,那么做起来可能会更快

for line in f.readlines():

相关问题 更多 >