]> arthur.barton.de Git - netdata.git/blob - plugins.d/loopsleepms.sh.inc
Renamed charts.d to plugins.d
[netdata.git] / plugins.d / loopsleepms.sh.inc
1 #!/bin/sh
2
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
6 # loop you need.
7
8 LOOPSLEEPMS_HIGHRES=2
9 LOOPSLEEPMS_LASTRUN=0
10 LOOPSLEEPMS_LASTSLEEP=0
11 loopsleepms() {
12         # the time in seconds to wait, as the first argument
13         local t=$1
14
15         # check if high resolution timer is supported
16         if [ $LOOPSLEEPMS_HIGHRES -eq 2 ]
17         then
18                 LOOPSLEEPMS_HIGHRES=1
19                 test `date +%N` = "%N" && LOOPSLEEPMS_HIGHRES=0
20         fi
21
22         # if high resolution is not supported
23         # just sleep the time requested, in seconds
24         if [ $LOOPSLEEPMS_HIGHRES -eq 0 ]
25         then
26                 sleep $t
27                 return
28         fi
29
30         # get the current time
31         local d=`date +'%s.%N'`
32         local s=`echo $d | cut -d '.' -f 1`
33         local m=`echo $d | cut -d '.' -f 2 | cut -b 1-3`
34         local now="$s$m" # milliseconds since epoch (1-1-1970)
35
36         # calculate required sleep in ms
37         t=$((t * 1000))
38
39         # this is our first run
40         # just wait the requested time
41         test $LOOPSLEEPMS_LASTRUN -eq 0 && LOOPSLEEPMS_LASTRUN=$now
42
43         # calculate ms since last run
44         local workms=$((now - LOOPSLEEPMS_LASTRUN - LOOPSLEEPMS_LASTSLEEP))
45         # echo "# last loop's work took $workms ms"
46
47         # calculate ms to sleep
48         local mstosleep=$((t - workms))
49         # echo "# mstosleep is $mstosleep ms"
50         
51         # if we are too slow, sleep some time
52         test $mstosleep -lt 100 && mstosleep=100
53
54         local s=$((mstosleep / 1000))
55         local m=$((mstosleep - (s * 1000)))
56
57         # echo "# sleeping $s.$m"
58         # echo
59         sleep $s.$m
60
61         # keep the values we need
62         # for our next run
63         LOOPSLEEPMS_LASTRUN=$now
64         LOOPSLEEPMS_LASTSLEEP=$mstosleep
65 }