I am new to OS as it was introduced to us very recently. we have bash code to run as our lap experiments. my last task was to code a program to print whether a number is prime or not. i coded it first in cpp because i am comfortable in cpp. and then coded same in bash after lot of googling. but my bash code is very slower than the cpp code.
I wrote a cpp code to check whether a number is prime or not. cpp code :
#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;
}
I wrote the same code in 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
but cpp code is very fast and bash code is very slow here is terminal input and output
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.
I have no idea why is this happening?
The C++ as other compiled languages have for sure a better performance with respect to interpreted languages like bash, sh, python.
This because when you use a compiled program, only a process is launched, while when you run an interpreted program it instatiates a great number of subprocesses also for basic operation.
So is trivial that c++ program is faster than the bash one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With