bug-bash
[Top][All Lists]
Advanced

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

RE: Bug/limitation in 'time'


From: Bruce Dawson
Subject: RE: Bug/limitation in 'time'
Date: Sat, 16 Mar 2013 19:18:40 -0700

Yep, we've changed our loops to use roughly that syntax. Unfortunately a lot
of online resources recommend the $(expr) technique. My understanding is
that using $(expr) is more portable, because i-- is bash specific, but I
don't really know.

-----Original Message-----
From: Chris Down [mailto:chris@chrisdown.name] 
Sent: Saturday, March 16, 2013 6:58 PM
To: Bruce Dawson
Cc: bug-bash@gnu.org; bash@packages.debian.org
Subject: Re: Bug/limitation in 'time'

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"
    }

Best,

Chris




reply via email to

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