The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #3 (permalink)  
Old 02-11-2009
cfajohnson's Avatar
cfajohnson cfajohnson is online now Forum Advisor  
Shell programmer, author
  
 

Join Date: Mar 2007
Location: Toronto, Canada
Posts: 2,378
Quote:
Originally Posted by csmklee View Post
I wrote a func to calculcate integers difference in csv.

Please put code inside [code] tags.
Quote:
Code:
getSegLatency() {
latencies=0$1
E2E=0`echo $2 | sed 's/\.000000//g'`

External commands are slow; there's no need for sed:


Code:
E2E=0${2%.*}

Quote:

Code:
integer segLatency=0

There is no standard command integer (and it's unnecessary).
Quote:

Code:
set -A arr `echo $latencies | sed 's/\.000000//g' | sed 's/,/ /g'`

No need for sed.

If you are using bash or ksh93, you can do that with:


Code:
IFS=,
arr=( $latencies )
IFS=$' \t\n'

Quote:

Code:
res=${arr[0]}
integer i=1
while ((i < ${#arr[*]})); do

The standard syntax is:


Code:
while [ $i -lt ${#arr[*]} ]; do

Quote:

Code:

((segLatency=${arr[$i]} - ${arr[$i - 1]}));

The standard syntax is:


Code:
segLatency=$(( ${arr[$i]} - ${arr[$i - 1]} ))

Quote:

Code:
res="$res,$segLatency"
(( i = i + 1));

The standard syntax is:


Code:
i=$(( $i + 1 ))

Quote:
Code:
done
((segLatency=$E2E - ${arr[$i - 1]}));

See previous note.
Quote:

Code:
res="$res,$segLatency"
echo $res
}

in which the number of elements in $1 may vary
e.g. when i call like:
getSegLatency 1.000000,4.000000,6.000000,7.000000 11.000000
i'll get:
3,2,1,4

With your code and that input, I get:

Code:
01,3,2,1,2

Quote:

It works well but the performance is slow.

Is there any way to polish the script to run faster?

It seems reasonably snappy to me, despite the unnecessary use of sed


Code:
getSegLatency() {
  IFS=,
  set -- $*
  IFS=$' \t\n'
  result=$(
    while [ $# -ge 2 ]
    do
      printf "%d," $(( (${1%.*} - ${2%.*}) * -1 ))
      shift
   done )
   printf "%s\n" ${result%,}
}


Last edited by cfajohnson; 02-11-2009 at 05:20 PM..