6

One of the functions in my node.js app is calling an external API using the fetch function. I am trying to find the most accurate way to measure the response time for the said API.

i am using the "Date" method to do it:

     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);

Is there a better\more accurate way to do it with fetch?

Ofer B
  • 369
  • 2
  • 5
  • 14

2 Answers2

6

You can use console.time & console.timeEnd as:

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

It will print the time elapsed like

timer1: 0.105ms
Shivaji Mutkule
  • 1,020
  • 1
  • 15
  • 28
2

In case you want to get the number as variable but not printing it out

    const start = Date.now();
    const response = await fetch(url);
    const secSpent = (Date.now() - start) / 1000; // <---
tom10271
  • 4,222
  • 5
  • 33
  • 62