我正在用 C 编写代码以在 enwik8 和 enwik9 中执行一些正则表达式。出于基准测试目的,我还在其他语言中创建了相同的算法。问题是我的 C 代码做错了,因为它需要 40 秒,而 python 和其他代码只需要 10 秒。
我忘记了什么?
#include <stdio.h>
#include <regex.h>
#define size 1024
int main(int argc, char **argv){
FILE *fp;
char line[size];
regex_t re;
int x;
const char *filename = "enwik8";
const char *strings[] = {"bhomeb", "bdearb", "bhouseb", "bdogb", "bcatb", "bblueb", "bredb", "bgreenb", "bboxb", "bwomanb", "bmanb", "bwomenb", "bfullb", "bemptyb", "bleftb", "brightb", "btopb", "bhelpb", "bneedb", "bwriteb", "breadb", "btalkb", "bgob", "bstayb", "bupperb", "blowerb", "bIb", "byoub", "bheb", "bsheb", "bweb", "btheyb"};
for(x = 0; x < 33; x++){
if(regcomp(&re, strings[x], REG_EXTENDED) != 0){
printf("Failed to compile regex '%s'n", strings[x]);
return -1;
}
fp = fopen(filename, "r");
if(fp == 0){
printf("Failed to open file %sn", filename);
return -1;
}
while((fgets(line, size, fp)) != NULL){
regexec(&re, line, 0, NULL, 0);
}
}
return 0;
}
文件访问和编译正则表达式可能是罪魁祸首。
- 编译一次正则表达式并将它们存储在数组中
- 打开文件
- 读一行
- 在其上运行每个已编译的正则表达式
- 关闭文件。