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