首先,我正在寻找优化,快速执行
我想从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;
}
根据这篇文章,读取输入线的速度比fgets
快?read()
功能似乎是解决方案。
数据输入就像:
100 C
1884231 B
8978456 Z
...
从文件中,我执行了我的程序,例如./myapp < mytext.txt
不可能知道有多少条目,可能是10、10000甚至更多。
此帖子
将所有铸件放在malloc和realloc上;它们不是必需的,并混乱了代码
所以,如果我使用动态阵列,我的应用程序会变慢。
这个想法是:
一个人读取整个输入,进入缓冲区。
处理该缓冲区的线路。
这是最快的解决方案。
如果有人会帮助我。预先感谢。
while (!feof(f))
总是错误的。而是使用此:
#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 bytesn", 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] = ' ';
// parse pos bytes of data in buf as a string
printf("read %zu bytesn", strlen(buf));
free(buf);
return EXIT_SUCCESS;
}
也许您可以使用 fseek (stdin, 0, SEEK_END)
进入标准输入流的末端,然后使用 ftell (stdin)
在字节中获取大小,然后分配内存以将所有这些保存在缓冲区中,然后再处理。它是内容。