| 1 | #!/bin/bash |
| 2 | # test-execution-time.sh |
| 3 | # Example by Erik Brandsberg, for testing execution time |
| 4 | #+ of certain operations. |
| 5 | # Referenced in the "Optimizations" section of "Miscellany" chapter. |
| 6 | |
| 7 | count=50000 |
| 8 | echo "Math tests" |
| 9 | echo "Math via \$(( ))" |
| 10 | time for (( i=0; i< $count; i++)) |
| 11 | do |
| 12 | result=$(( $i%2 )) |
| 13 | done |
| 14 | |
| 15 | echo "Math via *expr*:" |
| 16 | time for (( i=0; i< $count; i++)) |
| 17 | do |
| 18 | result=`expr "$i%2"` |
| 19 | done |
| 20 | |
| 21 | echo "Math via *let*:" |
| 22 | time for (( i=0; i< $count; i++)) |
| 23 | do |
| 24 | let result=$i%2 |
| 25 | done |
| 26 | |
| 27 | echo |
| 28 | echo "Conditional testing tests" |
| 29 | |
| 30 | echo "Test via case:" |
| 31 | time for (( i=0; i< $count; i++)) |
| 32 | do |
| 33 | case $(( $i%2 )) in |
| 34 | 0) : ;; |
| 35 | 1) : ;; |
| 36 | esac |
| 37 | done |
| 38 | |
| 39 | echo "Test with if [], no quotes:" |
| 40 | time for (( i=0; i< $count; i++)) |
| 41 | do |
| 42 | if [ $(( $i%2 )) = 0 ]; then |
| 43 | : |
| 44 | else |
| 45 | : |
| 46 | fi |
| 47 | done |
| 48 | |
| 49 | echo "Test with if [], quotes:" |
| 50 | time for (( i=0; i< $count; i++)) |
| 51 | do |
| 52 | if [ "$(( $i%2 ))" = "0" ]; then |
| 53 | : |
| 54 | else |
| 55 | : |
| 56 | fi |
| 57 | done |
| 58 | |
| 59 | echo "Test with if [], using -eq:" |
| 60 | time for (( i=0; i< $count; i++)) |
| 61 | do |
| 62 | if [ $(( $i%2 )) -eq 0 ]; then |
| 63 | : |
| 64 | else |
| 65 | : |
| 66 | fi |
| 67 | done |
| 68 | |
| 69 | exit $? |