【发布时间】:2020-07-08 16:09:24
【问题描述】:
我编写了这段代码来查找 C 文件中某个单词的出现次数。该代码运行良好。但肯定需要很多时间。为了统计一个单词在 650MB 大小的文件中出现的次数,需要 151.1 秒,这是很多时间。我想以 80MB/秒的速度处理它。如何提高时间复杂度?非常感谢
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE *fptr;
int l,i=0,count=0,total=0;
char name[100],n,word[25],k;
printf("\nEnter the word to be found:");
scanf("%s",word);
l=strlen(word);
printf("\nEnter the file name:");
scanf("%s",name);
fptr=fopen(name,"r");
if(fptr==NULL){
printf("\nProblem with opening the file");
exit(1);
}
n=fgetc(fptr);
while((feof(fptr)==0)){
if(n==toupper(word[i])||n==tolower(word[i])){
count++;
i++;
}
else if(n!=word[i]){
if(count>1){
fseek(fptr, -count, SEEK_CUR);
}
count=0;
i=0;
}
if(count==l){
total++;
count=0;
i=0;
}
n=fgetc(fptr);
}
if(total==0){
printf("\nThe word %s does not exist in the file",word);
}
printf("\nThe word %s occurred %d time(s) in the file",word,total);
}
【问题讨论】:
-
是受CPU限制,还是受I/O限制?
-
stackoverflow.com/questions/12629749/how-does-grep-run-so-fast
the time complexity of a file IO program?你确定你问的是算法的时间复杂度,而不仅仅是如何更快地做到这一点?时间复杂度和执行时间是相关的,但仍然不同。 -
你无法提高时间复杂度——它已经是 O(n),你只想让它更快。最直接的方法是大块读取文件——最好是一大块——然后在这些内存缓冲区上进行查找。
-
@KamilCuk 我只是希望它更快
-
@LeeDanielCrocker 这可能就是我想做的。我怎样才能做到这一点?