【发布时间】:2021-01-24 09:36:54
【问题描述】:
我是操作系统的新手,因为它是最近介绍给我们的。 我们有 bash 代码可以作为我们的单圈实验运行。 我的最后一项任务是编写一个程序来打印一个数字是否为素数。 我首先在 cpp 中对其进行了编码,因为我对 cpp 感到满意。然后在经过大量谷歌搜索后在 bash 中进行相同的编码。但是我的 bash 代码比 cpp 代码慢很多。
我写了一个 cpp 代码来检查一个数字是否是素数。 cpp代码:
#include <iostream>
using namespace std;
bool isprime(int a) {
if (a == 2 || a == 3)
return true;
if (a % 2 == 0)
return false;
if (a % 3 == 0)
return false;
for (int i = 1; (6 * i - 1) * (6 * i - i) <= a; ++i) {
if (a % (6 * i - 1) == 0)
return false;
if (a % (6 * i + 1) == 0)
return false;
}
return true;
}
int main() {
int n;
cin >> n;
cout << ((isprime(n)) ? "Prime" : "Not Prime") << endl;
return 0;
}
我在 bash (linux) 中编写了相同的代码:
read num
f=1
if test $num -eq 2
then f=1
elif test $num -eq 3
then f=1
elif test `expr $num % 2` -eq 0
then f=0
elif test `expr $num % 3` -eq 0
then f=0
else
for (( i=1; $((`expr i\*6-1`))**2 <= num; i++))
do
t=`expr $i \* 6 - 1`
if test `expr $num % $t` -eq 0
then
f=0
fi
t=`expr $i \* 6 + 1`
if test `expr $num % $t` -eq 0
then
f=0
fi
done
fi
if test $f -eq 1
then
echo 'Prime'
else
echo 'Not-Prime'
fi
但是 cpp 代码非常快,而 bash 代码非常慢 这里是终端输入和输出
a@a:~/Cp$ cat > input
1000000007
^?^C
a@a:~/Cp$ time ./a.out < input
Prime
real 0m0.003s
user 0m0.003s
sys 0m0.000s
a@a:~/Cp$ time ./prog.sh <input
^C
real 0m8.258s
user 0m5.906s
sys 0m2.794s
a@a:~/Cp$ # I interrupted the execution.
我不知道为什么会这样?
【问题讨论】:
-
不确定您在这里的期望,您将 C++(一种编译语言)与 Bash(一种使用大量子进程进行基本处理的解释性语言)进行比较。当然 C++ 会更快。
-
请检查for循环,如果条件写得不好,它可能会在for循环中停留无限时间。我建议你单独检查一下情况。
-
如果你不调用
expr(子shell)并使用bash内部数学来代替,bash会变得更快。 -
@ArshdeepSingh :在 bash 版本的循环体内,您正在创建 4 个子进程(在每次迭代中!)。如果您从 C++ 中执行此操作,它也会很慢。
-
不要使用反引号,而是使用
$(..)。并且不要使用expr。曾经。忘记它的存在。只需if ((num % t == 0)); then等。
标签: c++ bash performance performance-testing