使用 Node.js 中的 fetch 测量 API 响应时间

Ofe*_*r B 7 performance-testing node.js fetch-api

我的 Node.js 应用程序中的功能之一是使用 fetch 函数调用外部 API。我正在尝试找到最准确的方法来测量上述 API 的响应时间。

我正在使用“日期”方法来做到这一点:

     let start_time = new Date().getTime();
      fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then((res) => {
    return res.json();
  })
.then((data) => {
  console.log('Response time:', new Date().getTime() - start_time);
Run Code Online (Sandbox Code Playgroud)

有没有更好\更准确的方法来执行 fetch?

Shi*_*ule 7

您可以将 console.time 和 console.timeEnd 用作:

    console.time("timer1");
      fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then((res) => {
    return res.json();
  })
.then((data) => {
  console.timeEnd("timer1");
Run Code Online (Sandbox Code Playgroud)

它会打印经过的时间,例如

timer1: 0.105ms
Run Code Online (Sandbox Code Playgroud)