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 Down
Subject: Re: Bug/limitation in 'time'
Date: Sun, 17 Mar 2013 09:57:49 +0800
User-agent: Mutt/1.5.21 (2010-09-15)

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

Attachment: pgpKIEZ0w8bhC.pgp
Description: PGP signature


reply via email to

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