]> arthur.barton.de Git - netdata.git/blob - plugins.d/loopsleepms.sh.inc
Merge remote-tracking branch 'upstream/master' into health
[netdata.git] / plugins.d / loopsleepms.sh.inc
1 # no need for shebang - this file is included from other scripts
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 LOOPSLEEP_DATE="$(which date)"
9 if [ -z "$LOOPSLEEP_DATE" ]
10     then
11     echo >&2 "$0: ERROR: Cannot find the command 'date' in the system path."
12     exit 1
13 fi
14
15 LOOPSLEEPMS_LASTRUN=0
16 LOOPSLEEPMS_LASTSLEEP=0
17 LOOPSLEEPMS_LASTWORK=0
18
19 LOOPSLEEPMS_HIGHRES=1
20 test "$($LOOPSLEEP_DATE +%N)" = "%N" && LOOPSLEEPMS_HIGHRES=0
21
22 now_ms=
23 current_time_ms() {
24     # if high resolution is not supported
25     # just sleep the time requested, in seconds
26     if [ $LOOPSLEEPMS_HIGHRES -eq 0 ]
27     then
28         now_ms="$($LOOPSLEEP_DATE +'%s')000"
29     else
30         now_ms="$(( $( $LOOPSLEEP_DATE +'%s * 1000 + %-N / 1000000' ) ))"
31     fi
32 }
33
34 loopsleepms() {
35     local tellwork=0 t="$1" div s m now mstosleep
36
37     if [ "$t" = "tellwork" ]
38     then
39         tellwork=1
40         shift
41         t="$1"
42     fi
43     div="${2-100}"
44
45     # $t = the time in seconds to wait
46
47     # if high resolution is not supported
48     # just sleep the time requested, in seconds
49     if [ $LOOPSLEEPMS_HIGHRES -eq 0 ]
50     then
51         sleep $t
52         return
53     fi
54
55     # get the current time, in ms
56     # milliseconds since epoch (1-1-1970)
57     now="$(( $( $LOOPSLEEP_DATE +'%s * 1000 + %-N / 1000000' ) ))"
58
59     # calculate required sleep in ms
60     t=$((t * 1000 * div / 100))
61
62     # this is our first run
63     # just wait the requested time
64     test $LOOPSLEEPMS_LASTRUN -eq 0 && LOOPSLEEPMS_LASTRUN=$now
65
66     # calculate ms since last run
67     LOOPSLEEPMS_LASTWORK=$((now - LOOPSLEEPMS_LASTRUN - LOOPSLEEPMS_LASTSLEEP))
68     # echo "# last loop's work took $LOOPSLEEPMS_LASTWORK ms"
69
70     # calculate ms to sleep
71     mstosleep=$(( t - LOOPSLEEPMS_LASTWORK ))
72     # echo "# mstosleep is $mstosleep ms"
73
74     # if we are too slow, sleep some time
75     test $mstosleep -lt 200 && mstosleep=200
76
77     s=$((mstosleep / 1000))
78     m=$((mstosleep - (s * 1000)))
79
80     test $tellwork -eq 1 && echo >&2 " >>> PERFORMANCE >>> WORK TOOK $LOOPSLEEPMS_LASTWORK ms ( $((LOOPSLEEPMS_LASTWORK * 100 / 1000)).$((LOOPSLEEPMS_LASTWORK % 10))% cpu ) >>> SLEEPING $mstosleep ms"
81
82     # echo "# sleeping $s.$m"
83     # echo
84     sleep $s.$m
85
86     # keep the values we need
87     # for our next run
88     LOOPSLEEPMS_LASTRUN=$now
89     LOOPSLEEPMS_LASTSLEEP=$mstosleep
90 }