Is BASH really slow?

I solved this issue on SPOJ - http://www.spoj.com/problems/ALICESIE/

What makes you think about typing (n + 1) / 2

This is my C code that goes through 0.03s

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

so far this is my BASH code which gives a time limit (i.e.> 1s)

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

Can anyone tell me why this is happening? Is BASH really slow? Thanks.

+6
source share
3 answers

Bash slowly performs a number crunch. But that's not what Bash was designed for.

Bash hacks a script very quickly to automate some repetitive actions. Quickly change the failed Bash script and run it again. Quickly find out exactly what the Bash script does (as opposed to having to look for the source for the C executable you are looking for).

And this list goes on.

C and Bash are two very different breeds of languages ​​and environments. If you complain about the slow execution of Bash, you are using it for the wrong problem.

"Do not complain that the screwdriver sucks in when you insert a nail into the wall."

+4
source

You are compiling compiled code with script language (Bash).

Bash scripts will always be slower than compiled code because they need to be interpreted.

As you probably know, in order to run code written in C, you first need to compile it. When it comes to Bash scripts, you don’t need to read it, the code is just "readable on the fly." Thus, Bash is slower than C.

+2
source

Bash is slower than C due to the reasons given in other answers, but this does not explain what is happening here. I suspect that you allow one of your read hang forever, up to a timeout. When I implement this:

 #!/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 

It does not take a lot of time:

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

You can force the read statements to be disabled by using the -t flag to read , for example:

 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 } 
+2
source

All Articles