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
10 LOOPSLEEPMS_LASTSLEEP=0
11 LOOPSLEEPMS_LASTWORK=0
15 test `date +%N` = "%N" && LOOPSLEEPMS_HIGHRES=0
20 # check if high resolution timer is supported
21 test $LOOPSLEEPMS_HIGHRES -eq 2 && check_high_res
23 # if high resolution is not supported
24 # just sleep the time requested, in seconds
25 if [ $LOOPSLEEPMS_HIGHRES -eq 0 ]
27 local s="`date +'%s'`"
30 local d="`date +'%s.%N'`"
31 local s="`echo $d | cut -d '.' -f 1`"
32 local m="`echo $d | cut -d '.' -f 2 | cut -b 1-3`"
39 if [ "$1" = "tellwork" ]
45 # the time in seconds to wait, as the first argument
48 # check if high resolution timer is supported
49 test $LOOPSLEEPMS_HIGHRES -eq 2 && check_high_res
51 # if high resolution is not supported
52 # just sleep the time requested, in seconds
53 if [ $LOOPSLEEPMS_HIGHRES -eq 0 ]
59 # get the current time
60 local d="`date +'%s.%N'`"
61 local s="`echo $d | cut -d '.' -f 1`"
62 local m="`echo $d | cut -d '.' -f 2 | cut -b 1-3`"
63 local now="$s$m" # milliseconds since epoch (1-1-1970)
65 # calculate required sleep in ms
68 # this is our first run
69 # just wait the requested time
70 test $LOOPSLEEPMS_LASTRUN -eq 0 && LOOPSLEEPMS_LASTRUN=$now
72 # calculate ms since last run
73 LOOPSLEEPMS_LASTWORK=$((now - LOOPSLEEPMS_LASTRUN - LOOPSLEEPMS_LASTSLEEP))
74 # echo "# last loop's work took $LOOPSLEEPMS_LASTWORK ms"
76 test $tellwork -eq 1 && echo >&2 " >>> PERFORMANCE >>> WORK TOOK $LOOPSLEEPMS_LASTWORK ms ( $((LOOPSLEEPMS_LASTWORK * 100 / 1000)).$((LOOPSLEEPMS_LASTWORK % 10))% cpu )"
78 # calculate ms to sleep
79 local mstosleep=$((t - LOOPSLEEPMS_LASTWORK))
80 # echo "# mstosleep is $mstosleep ms"
82 # if we are too slow, sleep some time
83 test $mstosleep -lt $((t / 2)) && mstosleep=$((t / 2))
85 local s=$((mstosleep / 1000))
86 local m=$((mstosleep - (s * 1000)))
88 # echo "# sleeping $s.$m"
92 # keep the values we need
94 LOOPSLEEPMS_LASTRUN=$now
95 LOOPSLEEPMS_LASTSLEEP=$mstosleep