bingtuag 发表于 2015-12-27 14:32:54

文件读取效率比较(Perl,Python,VBA)

  测试样本:
  http://files.cnblogs.com/files/metree/TextSample.7z
  背景介绍:
  文本数据的处理是文本数据挖掘的第一步,本文展示了如何通过Perl,Python和VBA逐行读取文本文件(不打印输出),以下代码都添加了程序计时功能,主要用于对比各编程语言读取文本效率。
  测试环境:
  1)输入文件:读取94M文本文件。
  2)测试环境:
  a) 操作系统:Win7 64bit / SSD硬盘 / i7-4900MQ cpu @ 2.80GHz / 16G内存;
  b) Perl环境:Strawberry Perl 5.18.2.1-64bit;(同时电脑也安装了Cygwin 32bit);
  c) Python环境:Python 3.3.5;
  d) VBA环境:Excel2013 64bit, VBA7.0(测试时只保留一个excel文件处于打开状态,这点很重要!);
  测试结果:
  1)在Strawberry Perl 5.18.2.1-64bit和Cygwin 32bit下读取同样文件分别耗时0.162s,0.128s。

  2)在Python3.3.5环境下,读取同样文本约耗时0.639s。

  3)excel VBA文本空载逐行读取耗时2.855s。

  通过以上测试:
  1) Cygwin环境下Perl的文本读取效率最高,为0.128s,VBA文本读取效率最低,为2.855s,两者相差20倍左右。
  2) Cygwin环境下Perl的文本读取效率比Python3.3.5高约5倍。
  3) 仅在文本读取效率方面,Perl语言优势明显。
  
  Perl逐行读取文本核心代码



use strict ;
use Time::HiRes qw(gettimeofday) ;
sub Test
{
# sec: seconds
# usec: microsecond
my ($start_sec, $start_usec) = gettimeofday() ;
#======================#
# Place your code here!#
#======================#

open MYFILE01,"/home/metree/a/CFGMML-RNC3014-192.168.1.9-20140408040026.txt" || die "cannot open the file: $!\n";
#======================#
    # Read text row by row #
    #======================#
while (<MYFILE01>)
    {
#print;
$_ = <MYFILE01>;
#print $_;
    }
close MYFILE01;
my ($end_sec, $end_usec) = gettimeofday() ;
# Compute time elipsed
my $timeDelta = ($end_usec - $start_usec) / 1000 + ($end_sec - $start_sec) * 1000;
print $timeDelta;
}
&Test() ;
1 ;
  Python逐行读取文本核心代码



import datetime
starttime = datetime.datetime.now()

#===================#
# do something here #
#===================#

f = open("d:\CFGMML-RNC3014-192.168.1.9-20140408040026.txt","r")
line = f.readline()
while line:
#print (line)
line = f.readline()

f.close
endtime = datetime.datetime.now()
interval=endtime - starttime
print (interval)
  VBA逐行读取文本核心代码



Sub VBAtextReadline()
Dim FileToOpenCsv
Dim Begin
Dim Over
Dim fso_SeqCsv
FileToOpenCsv = Application.GetOpenFilename("CSV文档(*.*),*.*", 1, "请选择需要导入的csv文件", , True)
If Not IsArray(FileToOpenCsv) Then
MsgBox "未选择任何文件!"
Exit Sub
End If
'开始计时
Begin = Timer
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8      
i = 0 '统计文本总行数
   
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set fso_SeqCsv = CreateObject("Scripting.FileSystemObject")
For i_FilesNumCsv = LBound(FileToOpenCsv) To UBound(FileToOpenCsv)      
Set SeqCsvFiles = fso_SeqCsv.OpenTextFile(FileToOpenCsv(i_FilesNumCsv), ForReading, True, TristateTrue)      
Do While Not SeqCsvFiles.AtEndOfLine            
SeqAlarm_Line = SeqCsvFiles.ReadLine
'pmSglAlarmAll = Split(SeqAlarm_Line, Chr(44), -1)
i = i + 1            
Loop
Next

Application.ScreenUpdating = True
Application.DisplayAlerts = True   

Over = Timer
MsgBox ("已运行完成!共运行" & Over - Begin & "s。" & "" & i)
End Sub
页: [1]
查看完整版本: 文件读取效率比较(Perl,Python,VBA)