首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Express如何测量小于1ms的时间?

问Express如何测量小于1ms的时间?
EN

Stack Overflow用户
提问于 2020-03-13 10:48:47
回答 2查看 52关注 0票数 1

我刚刚开始研究名为Express的Web框架,我发现当刷新由Express渲染的网页时,linux控制台上会显示如下日志。

代码语言:javascript
复制
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的吗?

我为我糟糕的英语感到抱歉。感谢您阅读我的问题!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-03-13 11:21:48

Express最常用的日志中间件是morgan。

根据morgan的source code,我们可以确定摩根从底层的NodeJS process.hrtime()函数获得纳秒精度的时间信息:

代码语言:javascript
复制
this._startAt = process.hrtime()

从NodeJS source code我们可以看到,它的process.hrtime()从libuv获取时间信息

代码语言:javascript
复制
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的实现:

代码语言:javascript
复制
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。

票数 3
EN

Stack Overflow用户

发布于 2020-03-13 11:01:48

Performance Timing API和process.hrtime()是node.js中的两个选项。

在查看node.js代码时,可以看出Express数据可能来自使用process.hrtime()的http库here和here。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60664240

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档