Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to time functions in JavaScript similar to Python timeit

How can I measure the execution time of functions in JavaScript? Preferably similar to Python timeit.

like image 441
camdenl Avatar asked Jun 05 '15 22:06

camdenl


People also ask

Is Timeit Python in seconds?

The Python timeit() method accepts the code as a string and returns the execution time in seconds. On the contrary, the default_timer() method returns the time of its execution.

What does %% time mean in Python?

%%time is a magic command. It's a part of IPython. %%time prints the wall time for the entire cell whereas %time gives you the time for first line only. Using %%time or %time prints 2 values: CPU Times.

How do you use %% Timeit in Jupyter?

The “%timeit” is a line magic command in which the code consists of a single line or should be written in the same line for measuring the execution time. In the “%timeit” command, the particular code is specified after the “%timeit” is separated by a space.


2 Answers

There is no built in module equivalent to timeit.py but you can easily time the execution of code yourself. You should use performance.now() rather than Date.now() as it is more accurate.

From the MDN docs:

The performance.now() method returns a DOMHighResTimeStamp, measured in milliseconds, accurate to five thousandths of a millisecond (5 microseconds)

var start = performance.now();

//do your things

var end = performance.now();
var duration = end - start;

You could then use that to build your own timing library like this:

function TimeIt() {
    var self = this;

    function howLong(iterations, testFunction) {
        var results = [];
        var total = 0;
        for (var i = 0; i < iterations; i++) {
            var start = performance.now();
            testFunction();
            var end = performance.now();
            var duration = end - start;
            results.push(duration);
            total += duration;
        }
        var result = {
                results : results,
                total : total,
                avg : total / results.length
        }
        return result;
    }
    self.howLong = howLong;
}

Which you would use like this:

var timeit = new TimeIt();

var foo = function() {
//do some things
};

var result = timeit.howLong(1000, foo);
console.log("avg: " + result.avg);
console.log("total: " + result.total);
like image 165
bhspencer Avatar answered Oct 26 '22 17:10

bhspencer


I haven't made a really deap search about it, but as far as I have searched, I haven't found anything. The simplest thing to do is, get time when the function starts, get time when it ends and substract one from the other(after using Date.parse to convert them in miliseconds) . It is certainly a naive solution but a working one.

like image 31
cs04iz1 Avatar answered Oct 26 '22 17:10

cs04iz1