From b6b70e471c2ef3e07bb6e7b49c04a2f18ca69c99 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Thu, 30 Nov 2023 00:05:48 +0100 Subject: [PATCH] Add os.cputime() (#159) And use it in microbench to get slightly more accurate results. --- quickjs-libc.c | 17 +++++++++++++++++ tests/microbench.js | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/quickjs-libc.c b/quickjs-libc.c index cb75da2..2420d9b 100644 --- a/quickjs-libc.c +++ b/quickjs-libc.c @@ -45,6 +45,7 @@ #include #include #include +#include #include #if defined(__APPLE__) @@ -1948,6 +1949,21 @@ static JSValue js_os_signal(JSContext *ctx, JSValueConst this_val, return JS_UNDEFINED; } +#ifndef _WIN32 +static JSValue js_os_cputime(JSContext *ctx, JSValueConst this_val, + int argc, JSValueConst *argv) +{ + struct rusage ru; + int64_t cputime; + + cputime = 0; + if (!getrusage(RUSAGE_SELF, &ru)) + cputime = (int64_t)ru.ru_utime.tv_sec * 1000000 + ru.ru_utime.tv_usec; + + return JS_NewInt64(ctx, cputime); +} +#endif + #if defined(__linux__) || defined(__APPLE__) static int64_t get_time_us(void) { @@ -3617,6 +3633,7 @@ static const JSCFunctionListEntry js_os_funcs[] = { OS_FLAG(SIGTSTP), OS_FLAG(SIGTTIN), OS_FLAG(SIGTTOU), + JS_CFUNC_DEF("cputime", 0, js_os_cputime ), #endif JS_CFUNC_DEF("now", 0, js_os_now ), JS_CFUNC_DEF("setTimeout", 2, js_os_setTimeout ), diff --git a/tests/microbench.js b/tests/microbench.js index 52108da..3ce6ed4 100644 --- a/tests/microbench.js +++ b/tests/microbench.js @@ -98,7 +98,7 @@ var clocks_per_sec = 1000000; var max_iterations = 100; var clock_threshold = 2000; /* favoring short measuring spans */ var min_n_argument = 1; -var get_clock = os.now; +var get_clock = os.cputime ?? os.now; function log_one(text, n, ti) { var ref;