0

作为输入,我有一行:

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

其中A - 整数,有多少个数字Array1,然后a b- 中的数字Array1,然后B - 整数,有多少个数字Array2c 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]);
    }

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

4

1 回答 1

0

在大多数情况下,我认为这个恒定因素不会有什么大不了的。但是如果你坚持改进它......你可以试试这个:

#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")确实比帕斯卡慢 2read(x)倍)如有必要,编写自己的例程来获取令牌(整数)。

如果它仍然太慢,请尝试使用内存映射文件而不是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

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


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

于 2013-02-19T11:40:37.670 回答