|
| 1 | +#include "Performance.h" |
| 2 | +#include "mach/mach_time.h" |
| 3 | + |
| 4 | +namespace charon { |
| 5 | + |
| 6 | +void Performance::init(napi_env env) { |
| 7 | + napi_value global, Performance, performance; |
| 8 | + |
| 9 | + napi_get_global(env, &global); |
| 10 | + |
| 11 | + const napi_property_descriptor properties[] = { |
| 12 | + { |
| 13 | + .utf8name = "now", |
| 14 | + .name = nullptr, |
| 15 | + .method = now, |
| 16 | + .getter = nullptr, |
| 17 | + .setter = nullptr, |
| 18 | + .value = nullptr, |
| 19 | + .attributes = napi_default, |
| 20 | + .data = nullptr, |
| 21 | + }, |
| 22 | + }; |
| 23 | + |
| 24 | + napi_define_class(env, "Performance", NAPI_AUTO_LENGTH, |
| 25 | + Performance::constructor, nullptr, 1, properties, |
| 26 | + &Performance); |
| 27 | + |
| 28 | + napi_new_instance(env, Performance, 0, nullptr, &performance); |
| 29 | + |
| 30 | + const napi_property_descriptor globalProperties[] = { |
| 31 | + { |
| 32 | + .utf8name = "performance", |
| 33 | + .name = nullptr, |
| 34 | + .method = nullptr, |
| 35 | + .getter = nullptr, |
| 36 | + .setter = nullptr, |
| 37 | + .value = performance, |
| 38 | + .attributes = napi_default, |
| 39 | + .data = nullptr, |
| 40 | + }, |
| 41 | + }; |
| 42 | + |
| 43 | + napi_define_properties(env, global, 1, globalProperties); |
| 44 | +} |
| 45 | + |
| 46 | +napi_value Performance::constructor(napi_env env, napi_callback_info cbinfo) { |
| 47 | + napi_value thisArg; |
| 48 | + napi_get_cb_info(env, cbinfo, nullptr, nullptr, &thisArg, nullptr); |
| 49 | + |
| 50 | + return thisArg; |
| 51 | +} |
| 52 | + |
| 53 | +napi_value Performance::now(napi_env env, napi_callback_info cbinfo) { |
| 54 | + uint64_t time = mach_absolute_time(); |
| 55 | + mach_timebase_info_data_t timebase; |
| 56 | + mach_timebase_info(&timebase); |
| 57 | + double nanoseconds = |
| 58 | + (double)time * (double)timebase.numer / (double)timebase.denom; |
| 59 | + double milliseconds = nanoseconds / 1000000.0; |
| 60 | + |
| 61 | + napi_value result; |
| 62 | + napi_create_double(env, milliseconds, &result); |
| 63 | + return result; |
| 64 | +} |
| 65 | + |
| 66 | +} // namespace charon |
0 commit comments