How do you calculate the time it takes for a function to run?

Problem

I need to know how long it takes to execute a command in milliseconds.

Solution #1

``````var startTime = performance.now()

doSomething()   // <---- measured code goes between startTime and endTime

var endTime = performance.now()

console.log(`Call to doSomething took \${endTime - startTime} milliseconds`)
``````

importing performance

``````const { performance } = require('perf_hooks');
``````
``````console.time('doSomething')

doSomething()   // <---- The function you're measuring time for

console.timeEnd('doSomething')
``````

The string given to the time() and timeEnd() functions must be identical (for the timer to finish as expected).

Solution #2

use new Date().getTime()

ex.

``````var start = new Date().getTime();

for (i = 0; i < 50000; ++i) {
// do something
}

var end = new Date().getTime();
var time = end - start;
``````

Solution #3

Use performance.now():

``````<script>
var a = performance.now();
var b = performance.now();
alert('It took ' + (b - a) + ' ms.');
</script>
``````

It works on:

console. You may be able to make time, but it is not standard:

Apart from browser support, performance.now, which appears to be a stripped-down version of console, appears to have the ability to deliver more precise timings. time.

Also, NEVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER EVER When the user does not have an accurate system time, we will get invalid results, such as “negative timing”:

(Go to Gmail and set your system clock to a year ago so we can all laugh.) Perhaps one day we’ll have a JS Date Hall of Shame.)

The only time you’ll use Date is to show the user the time on his system clock. Not when you’re trying to tell time or measure something.

Solution #4

You can use your browser’s profiling tools or console commands like console.time() and console.timeEnd to get function execution time on your local development workstation ().

JavaScript profilers are included in all current browsers. Because you don’t have to change your existing code, which could alter the function’s execution time, these profilers should provide the most accurate measurement.

Alternatively, on your development machine, you can add instrumentation to your code with console. time() and console are two useful functions. timeEnd(). These functions, supported in Firefox11+, Chrome2+ and IE11+, report on timers that you start/stop via console. time(). time() takes a user-defined timer name as an argument, and timeEnd() then reports on the execution time since the timer started:

``````function a() {
console.time("mytimer");
... do stuff ...
var dur = console.timeEnd("myTimer"); // NOTE: dur only works in FF
}
``````

Only Firefox returns the elapsed time when calling timeEnd(). The result is simply reported to the developer console by the other browsers: the return value of timeEnd() is undefined.

You’ll need to instrument your code if you wish to get function execution time in the wild. There are a few options available to you. By requesting new Date, you can easily save the start and end times (). getTime():

``````function a() {
var start = new Date().getTime();
... do stuff ...
var end = new Date().getTime();
var dur = end - start;
}
``````

The Date object, on the other hand, has a millisecond resolution and will be affected by any changes in the OS’s system clock. There is a better alternative with current browsers.

The High Resolution Time, also known as window.performance.now, is a better alternative (). The now() method is superior than the old Date method. getTime() is useful in two ways:

Now() can be used practically anywhere that new Date can (). + new Date andt Date, + getTime(), + new Date, + new Date, + new Date, + new Date, + are() at the moment. Date and now() times cannot be mixed because Date is based on unix-epoch (the number of milliseconds since 1970) and now() is the number of milliseconds since your page navigation began (so it will be much smaller than Date).

An example of how to use now() is as follows:

``````function a() {
var start = window.performance.now();
... do stuff ...
var end = window.performance.now();
var dur = end - start;
}
``````

Chrome stable, Firefox 15+, and Internet Explorer 10 all support now(). Polyfills are also available in a variety of sizes.

UserTiming is another approach for measuring execution time in the wild. UserTiming works in the same way as console.time() and console.timeEnd(), but it uses the same High Resolution Timestamp as now() (for a sub-millisecond monotonically growing clock) and stores the timestamps and durations to the PerformanceTimeline.

Marks (timestamps) and measurements are notions in UserTiming (durations). You can define as many of each as you wish, and the PerformanceTimeline will display them.

You call mark to save a timestamp (startMarkName). Simply call measure to retrieve the time since your first mark (measurename, startMarkname). The duration is then saved in the PerformanceTimeline alongside your marks.

``````function a() {
window.performance.mark("start");
... do stuff ...
window.performance.measure("myfunctionduration", "start");
}

// duration is window.performance.getEntriesByName("myfunctionduration", "measure")[0];
``````

UserTiming is available in Internet Explorer 10 and Chrome 25. A polyfill is also available (which I wrote).

Solution #5

You should utilize the Performance interface to acquire precise values. It’s compatible with the most recent versions of Firefox, Chrome, Opera, and Internet Explorer. Here’s an example of how it can be used:

``````var performance = window.performance;
var t0 = performance.now();
doWork();
var t1 = performance.now();
console.log("Call to doWork took " + (t1 - t0) + " milliseconds.")
``````

Date.getTime() and console.time() are ineffective for determining exact execution times. If a quick rough estimate is acceptable to you, you can use them. By rough estimate, I mean a 15-60 ms difference from real time.

Check out this fantastic post on calculating JavaScript execution time. The author also provides a few of useful links about JavaScript time accuracy.