Skip to content

Commit affa51e

Browse files
committed
util: refine load calculating
Signed-off-by: He Xian <hexian000@outlook.com>
1 parent 7ea0240 commit affa51e

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

src/util.c

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,10 @@ void daemonize(
384384
slog_setoutput(SLOG_OUTPUT_SYSLOG, "kcptun-libev");
385385
}
386386

387+
#define READ_TIMESPEC(ts) \
388+
((int_fast64_t)(ts).tv_sec * INT64_C(1000000000) + \
389+
(int_fast64_t)(ts).tv_nsec)
390+
387391
double thread_load(void)
388392
{
389393
static _Thread_local struct {
@@ -399,17 +403,18 @@ double thread_load(void)
399403
return load;
400404
}
401405
if (last.set) {
402-
const double total =
403-
(double)(monotime.tv_sec - last.monotime.tv_sec) +
404-
(double)(monotime.tv_nsec - last.monotime.tv_nsec) *
405-
1e-9;
406-
const double busy =
407-
(double)(cputime.tv_sec - last.cputime.tv_sec) +
408-
(double)(cputime.tv_nsec - last.cputime.tv_nsec) * 1e-9;
409-
load = busy / total;
406+
const int_fast64_t total =
407+
READ_TIMESPEC(monotime) - READ_TIMESPEC(last.monotime);
408+
const int_fast64_t busy =
409+
READ_TIMESPEC(cputime) - READ_TIMESPEC(last.cputime);
410+
if (busy > 0 && total > 0 && busy <= total) {
411+
load = (double)busy / (double)total;
412+
}
410413
}
411414
last.monotime = monotime;
412415
last.cputime = cputime;
413416
last.set = true;
414417
return load;
415418
}
419+
420+
#undef READ_TIMESPEC

0 commit comments

Comments
 (0)