Skip to content

Commit b6b70e4

Browse files
authored
Add os.cputime() (#159)
And use it in microbench to get slightly more accurate results.
1 parent a140e1c commit b6b70e4

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

quickjs-libc.c

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
#include <dlfcn.h>
4646
#include <termios.h>
4747
#include <sys/ioctl.h>
48+
#include <sys/resource.h>
4849
#include <sys/wait.h>
4950

5051
#if defined(__APPLE__)
@@ -1948,6 +1949,21 @@ static JSValue js_os_signal(JSContext *ctx, JSValueConst this_val,
19481949
return JS_UNDEFINED;
19491950
}
19501951

1952+
#ifndef _WIN32
1953+
static JSValue js_os_cputime(JSContext *ctx, JSValueConst this_val,
1954+
int argc, JSValueConst *argv)
1955+
{
1956+
struct rusage ru;
1957+
int64_t cputime;
1958+
1959+
cputime = 0;
1960+
if (!getrusage(RUSAGE_SELF, &ru))
1961+
cputime = (int64_t)ru.ru_utime.tv_sec * 1000000 + ru.ru_utime.tv_usec;
1962+
1963+
return JS_NewInt64(ctx, cputime);
1964+
}
1965+
#endif
1966+
19511967
#if defined(__linux__) || defined(__APPLE__)
19521968
static int64_t get_time_us(void)
19531969
{
@@ -3617,6 +3633,7 @@ static const JSCFunctionListEntry js_os_funcs[] = {
36173633
OS_FLAG(SIGTSTP),
36183634
OS_FLAG(SIGTTIN),
36193635
OS_FLAG(SIGTTOU),
3636+
JS_CFUNC_DEF("cputime", 0, js_os_cputime ),
36203637
#endif
36213638
JS_CFUNC_DEF("now", 0, js_os_now ),
36223639
JS_CFUNC_DEF("setTimeout", 2, js_os_setTimeout ),

tests/microbench.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ var clocks_per_sec = 1000000;
9898
var max_iterations = 100;
9999
var clock_threshold = 2000; /* favoring short measuring spans */
100100
var min_n_argument = 1;
101-
var get_clock = os.now;
101+
var get_clock = os.cputime ?? os.now;
102102

103103
function log_one(text, n, ti) {
104104
var ref;

0 commit comments

Comments
 (0)