为什么bash比C快?

时间:2021-06-29 20:56:28

Out of curiosity, I did an adhoc benchmark between Bash and C:

出于好奇,我在Bash和C之间做了一个临时基准:

#!/bin/sh

for i in `seq 1 10000`; do
    true
done

On my machine, this runs in 0.02 seconds. Extremely fast. My understanding is that Bash parses the command and runs fork/exec. Therefore, I expected the following version, in C, to be much faster, since it doesn't need to do any parsing:

在我的机器上,这个运行时间是0。02秒。非常快。我的理解是Bash解析命令并运行fork/exec。因此,我希望C语言的下一个版本更快,因为它不需要做任何解析:

#include <unistd.h>

int main() {
    char *const argv[] = { "/bin/true", NULL };

    for (int i = 0; i < 10000; i++) {
        pid_t pid = fork();
        if (pid == 0) // child
                execv(argv[0], argv);

        int status = 0;
        waitpid(pid, &status, 0);
    }

    return 0;
}

To my astonishment, this took about 8 seconds! I figured Bash might be doing some clever optimization, if it had the insight that true was just a no-op and not worth calling at all. So I tried the same experiment with echo -n and sleep 0.0001 and got similar results. The commands are definitely getting called, but Bash doesn't have the fork/exec overhead that C has. Why is Bash so much faster in this case?

令我惊讶的是,这花了大约8秒!我认为Bash可能正在做一些巧妙的优化,如果它有这样的见解,那就是,true只是一个没有操作的东西,根本不值得调用。所以我用echo -n和sleep 0.0001做了同样的实验,得到了类似的结果。命令肯定会被调用,但是Bash没有C所具有的fork/exec开销。为什么在这种情况下Bash要快得多?

1 个解决方案

#1


11  

true and echo are both Bash builtin commands, so it doesn't need to spawn an external process to run them, making it much faster.

true和echo都是Bash内置命令,因此不需要生成外部进程来运行它们,从而使其运行速度更快。

$ type true
true is a shell builtin
$ type echo
echo is a shell builtin

#1


11  

true and echo are both Bash builtin commands, so it doesn't need to spawn an external process to run them, making it much faster.

true和echo都是Bash内置命令,因此不需要生成外部进程来运行它们,从而使其运行速度更快。

$ type true
true is a shell builtin
$ type echo
echo is a shell builtin