Skip to the solution
EasyPhone Screen4 min read

Why would you use performance.now() instead of Date.now() to measure how long a function takes to run?

364 views

The problem

Question presented to candidate: "If you wanted to measure how long a function takes to run, why would you reach for performance.now() instead of just calling Date.now() before and after it?"

What a strong answer should cover:

  • performance.now() returns a high-resolution timestamp, expressed as a float with sub-millisecond precision, relative to a fixed time origin -- not an absolute epoch value.
  • Date.now() returns whole milliseconds since the Unix epoch and is tied to the system wall clock, which can be adjusted (NTP sync, manual changes) while a measurement is in progress.
  • performance.now() is implemented as a monotonic clock -- it never goes backward, so it stays safe for measuring elapsed durations even if the wall clock is adjusted mid-measurement, unlike Date.now().
  • For a genuinely fast operation, Date.now() can report a 0ms delta simply because the operation finished inside the same millisecond tick, while performance.now() can report real, non-zero sub-millisecond timing for that same operation.
  • Real caveat worth naming: browsers deliberately coarsen and jitter performance.now()'s resolution as a Spectre-era security mitigation, so its resolution is not unlimited in a browser the way it can appear to be in a Node.js process.

Clarifying questions expected:

  • "Is this for browser code, Node.js code, or both -- the security-driven resolution coarsening only applies inside browsers."

Code / implementation expected: Yes -- a runnable snippet comparing both clocks' resolution and timing the same fast operation with each.

  • perf-api
  • tricky
  • real-world

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptDate.now() vs performance.now(): resolution, timing, and monotonicity (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 29 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

What is the difference between localStorage, sessionStorage, and cookies?

Continue