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 }
source share