gpt4 book ai didi

python read() from stdout 比逐行读取慢得多(吞咽?)

转载 作者:太空狗 更新时间:2023-10-29 17:34:11 29 4
gpt4 key购买 nike

我有一个运行可执行文件并将输出通过管道传输到我的子进程标准输出的 python SubProcess 调用。

在 stdout 数据相对较小(~2k 行)的情况下,逐行读取和作为一个 block 读取(stdout.read())之间的性能是可比较的......而 stdout.read() 稍微更快。

一旦数据变大(比如 30k+ 行),逐行读取的性能就会明显提高。

这是我的比较脚本:

proc=subprocess.Popen(executable,stdout=subprocess.PIPE)
tic=time.clock()
for line in (iter(proc.stdout.readline,b'')):
tmp.append(line)
print("line by line = %.2f"%(time.clock()-tic))

proc=subprocess.Popen(executable,stdout=subprocess.PIPE)
tic=time.clock()
fullFile=proc.stdout.read()
print("slurped = %.2f"%(time.clock()-tic))

这些是读取 ~96k 行(或 50mb 磁盘内存)的结果:

line by line = 5.48
slurped = 153.03

我不清楚为什么性能差异如此之大。我的期望是 read() 版本应该比逐行存储结果更快。当然,在实际情况下,我期待更快的逐行结果,因为在读取过程中可以完成大量的每行处理。

谁能告诉我 read() 的性能成本?

最佳答案

这不仅仅是 Python,没有缓冲的字符读取总是比读入行或大块慢。

考虑这两个简单的 C 程序:

[读取字符.c]

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

int main(void) {
FILE* fh = fopen("largefile.txt", "r");
if (fh == NULL) {
perror("Failed to open file largefile.txt");
exit(1);
}

int c;
c = fgetc(fh);
while (c != EOF) {
c = fgetc(fh);
}

return 0;
}

[readlines.c]

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

int main(void) {
FILE* fh = fopen("largefile.txt", "r");
if (fh == NULL) {
perror("Failed to open file largefile.txt");
exit(1);
}

char* s = (char*) malloc(120);
s = fgets(s, 120, fh);
while ((s != NULL) && !feof(fh)) {
s = fgets(s, 120, fh);
}

free(s);

return 0;
}

他们的结果(YMMW,largefile.txt 是 ~200MB 文本文件):

$ gcc readchars.c -o readchars
$ time ./readchars
./readchars 1.32s user 0.03s system 99% cpu 1.350 total
$ gcc readlines.c -o readlines
$ time ./readlines
./readlines 0.27s user 0.03s system 99% cpu 0.300 total

关于python read() from stdout 比逐行读取慢得多(吞咽?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21386464/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com