C 数组读取优化

标签 c

作为输入,我有一行:

2 6 7 5 1 2 3 4 5    
A a b B c d e f g

其中 A - 整数,Array1 中有多少个数字,然后 a b - Array1 中的数字,然后B - 整数,Array2 中有多少个数字,c d e f g - Array2 中的数字

我写了这段代码:

scanf("%d", &Alen); // read Array1 len
int posA[Alen];
for (i = 0; i < Alen; i++){
        scanf("%d", &posA[i]);//read Array1 numbers
    }

scanf("%d", &Blen);//read Array2 len
int posB[Blen];
for (i = 0; i < Blen; i++){//read Array2 numbers
        scanf("%d", &posB[i]);
    }

但是它太慢了(最慢,比我的程序,用这个数组做一些事情),所以可能有另一种方法来扫描这个数组,并快速完成这个?

最佳答案

我认为在大多数情况下这个常数因素并不重要。但如果你坚持改进它......你可以尝试这个:

#define BIGBIG_SIZE (10000000)
char* buffer=(char*)malloc(BIGBIG_SIZE); // make it big enough for your file.
                              // makes your life easier by making sure 
                              //the whole file could be read in once
fread( buffer , 1 , BIGBIG_SIZE , stdin );
sscanf( buffer , "%d", &a ); // from now on use sscanf to get from buffer instead of scanf()

这有时对我有用。 (我碰巧发现 scanf("%d") 确实比 Pascal 中的 read(x) 慢 2 倍)如果有必要,编写您自己的例程来获取 token (整数)。

如果仍然太慢,请尝试使用内存映射文件而不是 fread 到缓冲区中。

fd = open(FILEPATH, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
if (fd == -1) {
    perror("Error opening file for writing");
    exit(EXIT_FAILURE);
}
map = mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (map == MAP_FAILED) {
      close(fd);
      perror("Error mmapping the file");
      exit(EXIT_FAILURE);
}
// then you use sscanf() here

或您平台上的任何其他内存映射解决方案。

<小时/>

不过,我认为你不需要这些肮脏的把戏。

关于C 数组读取优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14956346/

相关文章:

c - C 中 char 的多个字符输入

c++ - 实时 TCP/IP 堆栈

c - 如何修改已传递给 C 函数的指针?

c - Linux 交叉编译库

c - 来自另一个目标的 add_custom_command

c - 在c中将int存储为字符串的有效方法

c - 为什么 gets() 不起作用?

c++ - 是否总是会有一个与您构建的 .dll 关联的 .lib(导入库)?

c - 在 c 中使用 p 线程编写并行快速排序

c - 在C中将字符串插入字符串