bug-bash
[Top][All Lists]
Advanced

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

Magnitude of Order "For Loop" performance deltas based on syntax change


From: Tom McCurdy
Subject: Magnitude of Order "For Loop" performance deltas based on syntax change
Date: Fri, 23 Sep 2016 19:15:12 -0400

Configuration Information [Automatically generated, do not change]:
Machine: x86_64
OS: linux-gnu
Compiler: gcc
Compilation CFLAGS:  -DPROGRAM='bash' -DCONF_HOSTTYPE='x86_64' -DCONF_OSTYPE='linux-gnu' -DCONF_MACHTYPE=$
uname output: Linux tom-VirtualBox 3.19.0-69-generic #77~14.04.1-Ubuntu SMP Tue Aug 30 01:29:21 UTC 2016 $
Machine Type: x86_64-pc-linux-gnu

Bash Version: 4.3
Patch Level: 11
Release Status: release

Description:
        Two nearly identical "For Loop" setups have large deltas in performance. See test program below. Was confirmed in IRC chat room by multiple users. Input is very noticeable with around 100,000 values.

The script was originally used to take an input file where the first line would determine how many int values were to follow. The remaining lines each had values that were sorted, and then the smallest difference between any two values were found.

Repeat-By:

Using script below comment/uncomment each method to test.
On my machine
Method-1 finishes in around 2 seconds
Method-2 finishes in around 72 seconds


---- Code Below (also attached script and test input file) ---
START=$(date +%s.%N)

read -r N && mapfile -t Pi < <(sort -n)
#echo "Done"

min=10000000

#Find the smallest difference between two numbers in sorted array with max array element = 10000000

# For-Loop Method-1: is super fast
 for (( i=0; i<N-1; i++ ))
     do
         current=${Pi[$i]}
         next=${Pi[$i+1]}
         diff=$(( next - current))
         if [ $diff -lt $min ]
         then
             min=$diff
         fi
 done

# For-Loop Method-2: is super slow
# for (( i=0; i<N-1; i++)); do
# if (( Pi[i+1] - Pi[i] < min )); then
# let min=Pi[i+1]-Pi[i]
# fi
# done


#The min difference between any two numbers in the array
echo "$min"

END=$(date +%s.%N)
DIFF=$(echo "$END - $START" | bc)
echo "$DIFF"


Thanks,
Tom     


--
Thomas McCurdy
Personal: tom.j.mccurdy@gmail.com

Attachment: longinput.txt
Description: Text document

Attachment: brokenForLoop.sh
Description: Bourne shell script


reply via email to

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