gpt4 book ai didi

C读取所有输入一次优化

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:59 25 4
gpt4 key购买 nike

首先我在寻找优化,快速执行

我想从 C 中的输入读取数据,所以这是我的代码 (Linux)

int main(void) {
char command_str[MAX_COMMAND_SIZE];

while (!feof(stdin)) {
fgets(command_str, MAX_COMMAND_SIZE, stdin);
// Parse data
}
return EXIT_SUCCESS;
}

根据这篇文章 Read a line of input faster than fgets ? read() 函数似乎是解决方案。

数据输入是这样的:

100 C
1884231 B
8978456 Z
...

从文件中,所以我像 ./myapp < mytext.txt 一样执行我的程序

无法知道有多少条目,可能是 10、10000 甚至更多。

From this post

Drop all the casts on malloc and realloc; they aren't necessary and clutter up the code

因此,如果我使用动态数组,我认为我的应用程序会变慢。

思路是:

  • Read the whole input in one go into a buffer.

  • Process the lines from that buffer.

  • That's the fastest possible solution.

如果有人愿意帮助我。提前致谢。

最佳答案

while (!feof(f)) is always wrong.改用这个:

#include <stdio.h>

int main(void) {
char command_str[MAX_COMMAND_SIZE];

while (fgets(command_str, MAX_COMMAND_SIZE, stdin)) {
// Parse data
}
return EXIT_SUCCESS;
}

以比 fgets() 更快的速度读取文件内容是可行的,但似乎超出了您的技能水平。先学习简单的东西。使用标准的逐行阅读器可以实现很多事情......很少有用例需要使用更高级的方法。

如果您想读取整个输入并将其解析为单个字符串,这里有一个适用于所有(有限)输入类型的通用解决方案:

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

int main(void) {
size_t pos = 0, size = 1025, nread;
char *buf0 = malloc(size);
char *buf = buf0;

for (;;) {
if (buf == NULL) {
fprintf(stderr, "not enough memory for %zu bytes\n", size);
free(buf0);
exit(1);
}
nread = fread(buf + pos, 1, size - pos - 1, stdin);
if (nread == 0)
break;

pos += nread;
/* Grow the buffer size exponentially (Fibonacci ratio) */
if (size - pos < size / 2)
size += size / 2 + size / 8;
buf = realloc(buf0 = buf, size);
}
buf[pos] = '\0';

// parse pos bytes of data in buf as a string
printf("read %zu bytes\n", strlen(buf));

free(buf);
return EXIT_SUCCESS;
}

关于C读取所有输入一次优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44737566/

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