gpt4 book ai didi

linux - 比 wc -l 更快更精确地计算行数的方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:28:47 27 4
gpt4 key购买 nike

通常我使用wc -l 来计算文件的行数。但是,对于 5*10^7 行的文件,我只得到 10^7 作为答案。我已经尝试了这里提出的所有建议: How to count lines in a document?但是它比 wc -l 花费更多的时间。

还有其他选择吗?

最佳答案

任何认真对待速度线计数的人都可以创建自己的实现:

#include <stdio.h>
#include <string.h>
#include <fcntl.h>

#define BUFFER_SIZE (1024 * 16)
char BUFFER[BUFFER_SIZE];

int main(int argc, char** argv) {
unsigned int lines = 0;
int fd, r;

if (argc > 1) {
char* file = argv[1];
if ((fd = open(file, O_RDONLY)) == -1) {
fprintf(stderr, "Unable to open file \"%s\".\n", file);
return 1;
}
} else {
fd = fileno(stdin);
}

while ((r = read(fd, BUFFER, BUFFER_SIZE)) > 0) {
char* p = BUFFER;
while ((p = memchr(p, '\n', (BUFFER + r) - p))) {
++p;
++lines;
}
}

close(fd);

if (r == -1) {
fprintf(stderr, "Read error.\n");
return 1;
}

printf("%d\n", lines);

return 0;
}

用法

a < input
... | a
a file

例子:

# time ./wc temp.txt
10000000

real 0m0.115s
user 0m0.102s
sys 0m0.014s

# time wc -l temp.txt
10000000 temp.txt

real 0m0.120s
user 0m0.103s
sys 0m0.016s

* 使用 GCC 4.8.2 在具有 AVX 和 SSE4.2 的系统上本地使用 -O3 编译的代码。

关于linux - 比 wc -l 更快更精确地计算行数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24159552/

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