3

我正在用 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[] = {"\bhome\b", "\bdear\b", "\bhouse\b", "\bdog\b", "\bcat\b", "\bblue\b", "\bred\b", "\bgreen\b", "\bbox\b", "\bwoman\b", "\bman\b", "\bwomen\b", "\bfull\b", "\bempty\b", "\bleft\b", "\bright\b", "\btop\b", "\bhelp\b", "\bneed\b", "\bwrite\b", "\bread\b", "\btalk\b", "\bgo\b", "\bstay\b", "\bupper\b", "\blower\b", "\bI\b", "\byou\b", "\bhe\b", "\bshe\b", "\bwe\b", "\bthey\b"};   

    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 %s\n", filename);

            return -1;
        }

        while((fgets(line, size, fp)) != NULL){
            regexec(&re, line, 0, NULL, 0);
        } 
    }

    return 0;
}
4

1 回答 1

3

文件访问和编译正则表达式可能是罪魁祸首。

  • 编译一次你的正则表达式并将它们存储在一个数组中
  • 打开文件
  • 读一行
  • 在它上面运行每个编译的正则表达式
  • 关闭文件。
于 2012-06-22T02:20:48.137 回答