我刚刚开始研究名为Express的Web框架,我发现当刷新由Express渲染的网页时,linux控制台上会显示如下日志。
GET / 304 20.768 ms - -
GET /stylesheets/style.css 304 0.521 ms - -
GET / 304 35.655 ms - -
GET /stylesheets/style.css 304 0.796 ms - -
GET / 304 33.824 ms - -
GET /stylesheets/style.css 304 1.023 ms - -我了解到Javascript可以测量的最短时间是1ms(https://en.wikipedia.org/wiki/System_time),比如Date()。
我认为日志是由Express本身显示的,所以我搜索了每个文件来查找日志中的单词,但没有找到这样的结果。我搜索了"304","ms","GET“作为关键字,但在我的项目目录中没有找到包括node_modules在内的任何内容。
哪个文件、函数或模块显示该日志?
或者,有人知道javascript是如何计算时间小于1ms的吗?
我为我糟糕的英语感到抱歉。感谢您阅读我的问题!
发布于 2020-03-13 11:21:48
Express最常用的日志中间件是morgan。
根据morgan的source code,我们可以确定摩根从底层的NodeJS process.hrtime()函数获得纳秒精度的时间信息:
this._startAt = process.hrtime()从NodeJS source code我们可以看到,它的process.hrtime()从libuv获取时间信息
static void Hrtime(const FunctionCallbackInfo<Value>& args) {
uint64_t t = uv_hrtime();
Local<ArrayBuffer> ab = args[0].As<Uint32Array>()->Buffer();
uint32_t* fields = static_cast<uint32_t*>(ab->GetBackingStore()->Data());
fields[0] = (t / NANOS_PER_SEC) >> 32;
fields[1] = (t / NANOS_PER_SEC) & 0xffffffff;
fields[2] = t % NANOS_PER_SEC;
}反过来,libuv直接从底层平台获取时间信息。例如,This就是Linux的实现:
uint64_t uv__hrtime(uv_clocktype_t type) {
static clock_t fast_clock_id = -1;
struct timespec t;
clock_t clock_id;
/* Prefer CLOCK_MONOTONIC_COARSE if available but only when it has
* millisecond granularity or better. CLOCK_MONOTONIC_COARSE is
* serviced entirely from the vDSO, whereas CLOCK_MONOTONIC may
* decide to make a costly system call.
*/
/* TODO(bnoordhuis) Use CLOCK_MONOTONIC_COARSE for UV_CLOCK_PRECISE
* when it has microsecond granularity or better (unlikely).
*/
if (type == UV_CLOCK_FAST && fast_clock_id == -1) {
if (clock_getres(CLOCK_MONOTONIC_COARSE, &t) == 0 &&
t.tv_nsec <= 1 * 1000 * 1000) {
fast_clock_id = CLOCK_MONOTONIC_COARSE;
} else {
fast_clock_id = CLOCK_MONOTONIC;
}
}
clock_id = CLOCK_MONOTONIC;
if (type == UV_CLOCK_FAST)
clock_id = fast_clock_id;
if (clock_gettime(clock_id, &t))
return 0; /* Not really possible. */
return t.tv_sec * (uint64_t) 1e9 + t.tv_nsec;
}因此,总而言之:纳秒精度时间是直接从操作系统检索的,只要是the operating system supports it。
发布于 2020-03-13 11:01:48
Performance Timing API和process.hrtime()是node.js中的两个选项。
在查看node.js代码时,可以看出Express数据可能来自使用process.hrtime()的http库here和here。
https://stackoverflow.com/questions/60664240
复制相似问题