为什么GNU Readline这么慢?

时间:2012-08-21 03:02:56

标签: c libreadline

我写了一个加密程序。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <readline/readline.h>

int main(void) {
    char * plain;
    char letter;
    int value;
    int index;

    plain = readline("Please input your plain text: ");
    printf("Please input your key (included negatives): ");
    scanf("%i", &value);

    for (index = 0; index < strlen(plain); index++) {
        letter = plain[index];

        if (letter >= 'A' && letter <= 'Z') {
            fprintf(stderr, "%c", (letter - 'A' + value) % 26 + 'A');
        }

        else if (letter >= 'a' && letter <= 'z') {
            fprintf(stderr, "%c", (letter - 'a' + value) % 26 + 'a');
        }
        else {
            fprintf(stderr, "%c", letter);
        }
    }
    fprintf(stderr, "\n");
    free(plain);
}

我做了一些基准测试:

biergaizi@localhost ~/learning_c/test $ time ./caesar_readline < lots_of_letters 2> c_readline_result > /dev/null

real    2m31.212s
user    2m30.776s
sys     0m0.165s

程序花费太多时间从标准输入中读取文本。如果我删除> /dev/null,我可以看到程序正在从标准输入读取,太慢了!

我还编写了没有GNU Readline的版本,速度非常快。

为什么呢?我该如何解决?

1 个答案:

答案 0 :(得分:0)

因为它提供的功能。

  

提供了一组供应用程序使用的函数   在输入时编辑命令行.Emacs和vi编辑   模式可用。

我认为你可以使用开放功能

if (!strcmp(*argv, "-"))
  fd = fileno(stdin);
else fd = open(*argv, O_RDONLY|O_NONBLOCK, 0);

并提供 - 作为文件名,如果你想从stdin读取