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" s m now mstosleep
37 if [ "$t" = "tellwork" ]
44 # $t = the time in seconds to wait
46 # if high resolution is not supported
47 # just sleep the time requested, in seconds
48 if [ $LOOPSLEEPMS_HIGHRES -eq 0 ]
54 # get the current time, in ms
55 # milliseconds since epoch (1-1-1970)
56 now="$(( $( $LOOPSLEEP_DATE +'%s * 1000 + %-N / 1000000' ) ))"
58 # calculate required sleep in ms
61 # this is our first run
62 # just wait the requested time
63 test $LOOPSLEEPMS_LASTRUN -eq 0 && LOOPSLEEPMS_LASTRUN=$now
65 # calculate ms since last run
66 LOOPSLEEPMS_LASTWORK=$((now - LOOPSLEEPMS_LASTRUN - LOOPSLEEPMS_LASTSLEEP))
67 # echo "# last loop's work took $LOOPSLEEPMS_LASTWORK ms"
69 test $tellwork -eq 1 && echo >&2 " >>> PERFORMANCE >>> WORK TOOK $LOOPSLEEPMS_LASTWORK ms ( $((LOOPSLEEPMS_LASTWORK * 100 / 1000)).$((LOOPSLEEPMS_LASTWORK % 10))% cpu )"
71 # calculate ms to sleep
72 mstosleep=$((t - LOOPSLEEPMS_LASTWORK))
73 # echo "# mstosleep is $mstosleep ms"
75 # if we are too slow, sleep some time
76 test $mstosleep -lt $((t / 2)) && mstosleep=$((t / 2))
78 s=$((mstosleep / 1000))
79 m=$((mstosleep - (s * 1000)))
81 # echo "# sleeping $s.$m"
85 # keep the values we need
87 LOOPSLEEPMS_LASTRUN=$now
88 LOOPSLEEPMS_LASTSLEEP=$mstosleep