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.
This commit is contained in:
Ben Noordhuis 2023-11-19 17:26:25 +01:00 committed by GitHub
parent 4727e40ac8
commit e49da8e96f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 5 deletions

View file

@ -1948,22 +1948,33 @@ static JSValue js_os_signal(JSContext *ctx, JSValueConst this_val,
} }
#if defined(__linux__) || defined(__APPLE__) #if defined(__linux__) || defined(__APPLE__)
static int64_t get_time_ms(void) static int64_t get_time_us(void)
{ {
struct timespec ts; struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts); clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000 + (ts.tv_nsec / 1000000); return (int64_t)ts.tv_sec * 1000000 + (ts.tv_nsec / 1000);
} }
#else #else
/* more portable, but does not work if the date is updated */ /* more portable, but does not work if the date is updated */
static int64_t get_time_ms(void) static int64_t get_time_us(void)
{ {
struct timeval tv; struct timeval tv;
gettimeofday(&tv, NULL); gettimeofday(&tv, NULL);
return (int64_t)tv.tv_sec * 1000 + (tv.tv_usec / 1000); return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
} }
#endif #endif
static int64_t get_time_ms(void)
{
return get_time_us() / 1000;
}
static JSValue js_os_now(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
return JS_NewInt64(ctx, get_time_us());
}
static void unlink_timer(JSRuntime *rt, JSOSTimer *th) static void unlink_timer(JSRuntime *rt, JSOSTimer *th)
{ {
if (th->link.prev) { if (th->link.prev) {
@ -3606,6 +3617,7 @@ static const JSCFunctionListEntry js_os_funcs[] = {
OS_FLAG(SIGTTIN), OS_FLAG(SIGTTIN),
OS_FLAG(SIGTTOU), OS_FLAG(SIGTTOU),
#endif #endif
JS_CFUNC_DEF("now", 0, js_os_now ),
JS_CFUNC_DEF("setTimeout", 2, js_os_setTimeout ), JS_CFUNC_DEF("setTimeout", 2, js_os_setTimeout ),
JS_CFUNC_DEF("clearTimeout", 1, js_os_clearTimeout ), JS_CFUNC_DEF("clearTimeout", 1, js_os_clearTimeout ),
JS_PROP_STRING_DEF("platform", OS_PLATFORM, 0 ), JS_PROP_STRING_DEF("platform", OS_PLATFORM, 0 ),

View file

@ -23,6 +23,7 @@
* THE SOFTWARE. * THE SOFTWARE.
*/ */
import * as std from "std"; import * as std from "std";
import * as os from "os";
function pad(str, n) { function pad(str, n) {
str += ""; str += "";
@ -97,7 +98,7 @@ var clocks_per_sec = 1000000;
var max_iterations = 100; var max_iterations = 100;
var clock_threshold = 2000; /* favoring short measuring spans */ var clock_threshold = 2000; /* favoring short measuring spans */
var min_n_argument = 1; var min_n_argument = 1;
var get_clock = Date.now; var get_clock = os.now;
function log_one(text, n, ti) { function log_one(text, n, ti) {
var ref; var ref;