I don't know how to do this. Javascript is single-threaded, so I can't run function and timer at the same time. How to check how much time my function executes?
Asked
Active
Viewed 652 times
0
-
1Use `console.time('identifier')` and `console.timeEnd('identifier')` – A1rPun Jun 11 '14 at 14:24
-
You could run it as a node process node
and use the unix's time command. – Hrishi Jun 11 '14 at 14:24 -
Note regarding the other post: If the function is asynchronous, `end` should be captured and compared against inside the callback. – Jonathan Lonowski Jun 11 '14 at 14:26
1 Answers
0
You can use the getTime()
method of the Date
object.
var start = new Date().getTime();
for (var i = 0; i < 100000; ++i) {
// work
}
var end = new Date().getTime();
var time = end - start;
console.log('Execution time: ' + time);
The start
is the moment when your code starts executing. The end
is the moment when it finishes execution. If you make the difference between those 2 moments you get the time it took for it to execute.
Also, taking into account the fact that in javascript you can pass functions as arguments, you can do something like this:
function profile(myCode) {
var start = new Date().getTime(); //the moment when execution starts
myCode(); //execute your code
var end = new Date().getTime(); // the moment when execution finishes
var time = end - start; // time it took
console.log('Execution time: ' + time); // output the time to console
return time; // return the time for further use
}

Andrei
- 3,086
- 2
- 19
- 24
-
-
1Probably I understand. My question was marked as dupe recently and you seem to have copied the accepted answer from original question. – nicael Jun 11 '14 at 14:27
-
I haven't copied any answer. Also, I don't see it marked as dupe. It could resemble other answers since it has only 3 lines of code. Oh well. – Andrei Jun 11 '14 at 14:30
-
-
-
-
Ok, I see it now. Seems that this change was not pushed to my browser. Yeah, it does resemble that answer but I didn't copy it. It is just common practice. Also I have added more explanation than that answer. – Andrei Jun 11 '14 at 14:35
-
-
Thank you! I just wanted to clarify a wrongful accusation. This answer was the only one in the last days so I don't care about rep anymore. – Andrei Jun 11 '14 at 14:40