bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Bug/limitation in 'time'


From: Chris F.A. Johnson
Subject: Re: Bug/limitation in 'time'
Date: Sat, 16 Mar 2013 22:15:50 -0400 (EDT)
User-agent: Alpine 2.00 (LMD 1167 2008-08-23)

On Sun, 17 Mar 2013, Chris Down wrote:

Hi Bruce,

On 2013-03-16 17:41, Bruce Dawson wrote:
I think it's important because when I hit this problem (using $(expr) for
looping in shell scripts is slow) I initially assumed that my task was not
CPU bound, because that is what 'time' told me. This then led me down the
wrong path in my investigation.

No comment on the issue itself, but this is just not a good way of writing bash
arithmetic loops:

#!/bin/bash
# Warning: this code is excessively slow
function ExprCount() {
                i=$1
                while [ $i -gt 0 ]; do
                                i=$(expr $i - 1)
                                #sleep 0.001
                done
                echo Just did $1 iterations using expr math
}
time ExprCount 1000

You're forking 1000 subshells for `expr' when you can quite easily do it on your
current shell. A better way would be to write it like this:

   ExprCount() {
       for (( i = $1 ; i > 0 ; i-- )); do
           :
       done
       echo "$1 iterations"
   }

   Or, in a POSIX-compliant manner:

ExprCount() {
  i=$1
  while [ $(( i -= 1 )) -ge 0 ]; do
    :
  done
  echo Just did $1 iterations using expr math
}

--
   Chris F.A. Johnson, <http://cfajohnson.com/>
   Author:
   Pro Bash Programming: Scripting the GNU/Linux Shell (2009, Apress)
   Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)



reply via email to

[Prev in Thread] Current Thread [Next in Thread]