3 # this function is used to sleep a fraction of a second
4 # it calculates the difference between every time is called
5 # and tries to align the sleep time to give you exactly the
8 LOOPSLEEP_DATE="$(which date)"
9 if [ -z "$LOOPSLEEP_DATE" ]
11 echo >&2 "$0: ERROR: Cannot find the command 'date' in the system path."
16 LOOPSLEEPMS_LASTSLEEP=0
17 LOOPSLEEPMS_LASTWORK=0
20 test "$($LOOPSLEEP_DATE +%N)" = "%N" && LOOPSLEEPMS_HIGHRES=0
24 # if high resolution is not supported
25 # just sleep the time requested, in seconds
26 if [ $LOOPSLEEPMS_HIGHRES -eq 0 ]
28 now_ms="$($LOOPSLEEP_DATE +'%s')000"
30 now_ms="$(( $( $LOOPSLEEP_DATE +'%s * 1000 + %-N / 1000000' ) ))"
35 local tellwork=0 t="$1" div s m now mstosleep
37 if [ "$t" = "tellwork" ]
45 # $t = the time in seconds to wait
47 # if high resolution is not supported
48 # just sleep the time requested, in seconds
49 if [ $LOOPSLEEPMS_HIGHRES -eq 0 ]
55 # get the current time, in ms
56 # milliseconds since epoch (1-1-1970)
57 now="$(( $( $LOOPSLEEP_DATE +'%s * 1000 + %-N / 1000000' ) ))"
59 # calculate required sleep in ms
60 t=$((t * 1000 * div / 100))
62 # this is our first run
63 # just wait the requested time
64 test $LOOPSLEEPMS_LASTRUN -eq 0 && LOOPSLEEPMS_LASTRUN=$now
66 # calculate ms since last run
67 LOOPSLEEPMS_LASTWORK=$((now - LOOPSLEEPMS_LASTRUN - LOOPSLEEPMS_LASTSLEEP))
68 # echo "# last loop's work took $LOOPSLEEPMS_LASTWORK ms"
70 # calculate ms to sleep
71 mstosleep=$(( t - LOOPSLEEPMS_LASTWORK ))
72 # echo "# mstosleep is $mstosleep ms"
74 # if we are too slow, sleep some time
75 test $mstosleep -lt 200 && mstosleep=200
77 s=$((mstosleep / 1000))
78 m=$((mstosleep - (s * 1000)))
80 test $tellwork -eq 1 && echo >&2 " >>> PERFORMANCE >>> WORK TOOK $LOOPSLEEPMS_LASTWORK ms ( $((LOOPSLEEPMS_LASTWORK * 100 / 1000)).$((LOOPSLEEPMS_LASTWORK % 10))% cpu ) >>> SLEEPING $mstosleep ms"
82 # echo "# sleeping $s.$m"
86 # keep the values we need
88 LOOPSLEEPMS_LASTRUN=$now
89 LOOPSLEEPMS_LASTSLEEP=$mstosleep