BASH很慢吗?

时间:2013-04-12 15:08:31

标签: bash

我在SPOJ上解决了这个问题 - http://www.spoj.com/problems/ALICESIE/

问题归结为打印(n + 1)/ 2

这是我传入0.03s的C代码

    #include <stdio.h>
    int main() {
        int test, n;
        scanf("%d", &test);
        while(test--) {
            scanf("%d", &n);
            printf("%d\n", (n + 1) >> 1);
        }
        return 0;
    }

虽然这是我的BASH代码,它给出了超出时间限制(即> 1s)

read test
while (( test-- ))
do
    read n
    echo "$(((n+1)/2))"
done 

任何人都可以告诉我为什么会这样吗? BASH很慢吗? 感谢。

4 个答案:

答案 0 :(得分:4)

Bash在执行数字运算时很慢。但这不是Bash的设计目标。

Bash非常非常快速编写脚本以自动执行某些重复操作。修改错误的Bash脚本并再次运行它很快。很快就能找到Bash脚本究竟在做什么(而不是必须寻找你正在查看的C可执行文件的源代码)。

列表继续。

C和Bash是两种截然不同的语言和环境。如果你抱怨Bash很慢,你就是用它来解决错误的问题。

“不要抱怨螺丝刀在将钉子钉入墙壁时很糟糕。”

答案 1 :(得分:2)

您将编译的代码与脚本语言(Bash)进行比较。

Bash脚本总是比编译代码慢,因为它们需要被解释。

您可能知道,为了运行用C编写的代码,首先需要编译它。说到Bash脚本,你不必阅读它,代码只是“即时阅读”。所以Bash比C慢。

答案 2 :(得分:2)

Bash比C慢,肯定是因为其他答案中给出的原因,但这并不能解释这里发生的事情。我怀疑你让你的一个read永远挂起,直到超时。当我实现这个:

#!/bin/bash

main() {
    local test
    local i
    local n
    read test
    for (( i=$test; i>0; i--)); do
        read n
        echo "$(((n+1)/2))"
    done
}

time {
    echo 1000
    printf '%d\n' {1002..2}
} | main

这不需要太多时间:

real    0m0.033s
user    0m0.029s
sys 0m0.013s

您可以强制read语句自行超时,-t标记为read,如下所示:

main() {
    local test
    local i
    local n
    read -t.3 test
    if [[ -z $test ]]; then
        echo "Failed to read a test value within 300ms."
        return 1
    }
    for (( i=$test; i>0; i--)); do
        read -t.3 n
        if [[ -z $n ]]; then
            echo "Failed to read a value for n within 300ms."
            return 1
        }
        echo "$(((n+1)/2))"
    done
}

答案 3 :(得分:0)

没有添加shebang。

#!/bin/bash

read test
while (( test-- ))
do
    read n
    echo "$(((n+1)/2))"
done 

我提交的这段代码在SPOJ中运行了0.14次,并被接受。除了shebang,我的问题代码没有其他区别!
(供读者使用)

相关问题