Skip to content

Commit

Permalink
Add os.cputime() (#159)
Browse files Browse the repository at this point in the history
And use it in microbench to get slightly more accurate results.
  • Loading branch information
bnoordhuis authored Nov 29, 2023
1 parent a140e1c commit b6b70e4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
17 changes: 17 additions & 0 deletions quickjs-libc.c
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
#include <dlfcn.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <sys/resource.h>
#include <sys/wait.h>

#if defined(__APPLE__)
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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 ),
Expand Down
2 changes: 1 addition & 1 deletion tests/microbench.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit b6b70e4

Please sign in to comment.