【发布时间】:2010-09-23 13:53:39
【问题描述】:
我有一个将近 900 万行的数据文件(很快就会超过 5 亿行),我正在寻找读取它的最快方法。五个对齐的列被填充并用空格分隔,所以我知道在每行的哪个位置查找我想要的两个字段。 我的 Python 例程需要 45 秒:
import sys,time
start = time.time()
filename = 'test.txt' # space-delimited, aligned columns
trans=[]
numax=0
for line in open(linefile,'r'):
nu=float(line[-23:-11]); S=float(line[-10:-1])
if nu>numax: numax=nu
trans.append((nu,S))
end=time.time()
print len(trans),'transitions read in %.1f secs' % (end-start)
print 'numax =',numax
而我在 C 中提出的例程是更令人愉悦的 4 秒:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define BPL 47
#define FILENAME "test.txt"
#define NTRANS 8858226
int main(void) {
size_t num;
unsigned long i;
char buf[BPL];
char* sp;
double *nu, *S;
double numax;
FILE *fp;
time_t start,end;
nu = (double *)malloc(NTRANS * sizeof(double));
S = (double *)malloc(NTRANS * sizeof(double));
start = time(NULL);
if ((fp=fopen(FILENAME,"rb"))!=NULL) {
i=0;
numax=0.;
do {
if (i==NTRANS) {break;}
num = fread(buf, 1, BPL, fp);
buf[BPL-1]='\0';
sp = &buf[BPL-10]; S[i] = atof(sp);
buf[BPL-11]='\0';
sp = &buf[BPL-23]; nu[i] = atof(sp);
if (nu[i]>numax) {numax=nu[i];}
++i;
} while (num == BPL);
fclose(fp);
end = time(NULL);
fprintf(stdout, "%d lines read; numax = %12.6f\n", (int)i, numax);
fprintf(stdout, "that took %.1f secs\n", difftime(end,start));
} else {
fprintf(stderr, "Error opening file %s\n", FILENAME);
free(nu); free(S);
return EXIT_FAILURE;
}
free(nu); free(S);
return EXIT_SUCCESS;
}
Fortran、C++ 和 Java 中的解决方案需要中等量的时间(27 秒、20 秒、8 秒)。 我的问题是:我在上面是否犯了任何令人发指的错误(特别是 C 代码)?有什么方法可以加快 Python 例程的速度吗?我很快意识到将我的数据存储在一个元组数组中比为每个条目实例化一个类要好。
【问题讨论】:
-
请解释一下你的 C 代码中的神奇数字(你从哪里得出 47 和 858226?)
-
你应该在你的 python 代码上运行分析器,看看它在哪里慢。此外,您应该尝试遵循 python 的 pep8 样式约定,它们使其更易于阅读。
-
sorry - BPL=47 是每行的字节数,包括 \n EOL 字符; 8588226 是文件中的总行数 - 所以我知道存储数据需要多少内存。
-
在python方面,我想你可以通过返回一个迭代器而不是构建一个数组来显着加快它。