Skip to content

Commit e49da8e

Browse files
authored
Unbreak microbench, add os.now() (#93)
The removal of the high-precision but non-standard clock source in commit 5af98ca broke microbench because Date.now() is not granular enough for the benchmark runner to make forward progress. This commit adds a new method to the os module that returns time with microsecond precision.
1 parent 4727e40 commit e49da8e

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

quickjs-libc.c

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1948,22 +1948,33 @@ static JSValue js_os_signal(JSContext *ctx, JSValueConst this_val,
19481948
}
19491949

19501950
#if defined(__linux__) || defined(__APPLE__)
1951-
static int64_t get_time_ms(void)
1951+
static int64_t get_time_us(void)
19521952
{
19531953
struct timespec ts;
19541954
clock_gettime(CLOCK_MONOTONIC, &ts);
1955-
return (uint64_t)ts.tv_sec * 1000 + (ts.tv_nsec / 1000000);
1955+
return (int64_t)ts.tv_sec * 1000000 + (ts.tv_nsec / 1000);
19561956
}
19571957
#else
19581958
/* more portable, but does not work if the date is updated */
1959-
static int64_t get_time_ms(void)
1959+
static int64_t get_time_us(void)
19601960
{
19611961
struct timeval tv;
19621962
gettimeofday(&tv, NULL);
1963-
return (int64_t)tv.tv_sec * 1000 + (tv.tv_usec / 1000);
1963+
return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
19641964
}
19651965
#endif
19661966

1967+
static int64_t get_time_ms(void)
1968+
{
1969+
return get_time_us() / 1000;
1970+
}
1971+
1972+
static JSValue js_os_now(JSContext *ctx, JSValueConst this_val,
1973+
int argc, JSValueConst *argv)
1974+
{
1975+
return JS_NewInt64(ctx, get_time_us());
1976+
}
1977+
19671978
static void unlink_timer(JSRuntime *rt, JSOSTimer *th)
19681979
{
19691980
if (th->link.prev) {
@@ -3606,6 +3617,7 @@ static const JSCFunctionListEntry js_os_funcs[] = {
36063617
OS_FLAG(SIGTTIN),
36073618
OS_FLAG(SIGTTOU),
36083619
#endif
3620+
JS_CFUNC_DEF("now", 0, js_os_now ),
36093621
JS_CFUNC_DEF("setTimeout", 2, js_os_setTimeout ),
36103622
JS_CFUNC_DEF("clearTimeout", 1, js_os_clearTimeout ),
36113623
JS_PROP_STRING_DEF("platform", OS_PLATFORM, 0 ),

tests/microbench.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
* THE SOFTWARE.
2424
*/
2525
import * as std from "std";
26+
import * as os from "os";
2627

2728
function pad(str, n) {
2829
str += "";
@@ -97,7 +98,7 @@ var clocks_per_sec = 1000000;
9798
var max_iterations = 100;
9899
var clock_threshold = 2000; /* favoring short measuring spans */
99100
var min_n_argument = 1;
100-
var get_clock = Date.now;
101+
var get_clock = os.now;
101102

102103
function log_one(text, n, ti) {
103104
var ref;

0 commit comments

Comments
 (0)