U Rogel
U Rogel

Reputation: 1941

function efficiency measuring javascript

I would like to check the efficiency of my functions, let's say to find a prime number, I wrote something like:

var counter = 0;
var myVar = setInterval(myTimer, 10)
function myTimer() {counter++}

//Function to be accessed
function isPrime(num){
    my function
}

var prime = isPrime(x);
clearInterval(myVar);
console.log(counter);

My problem is that counter = 0in the end

Interestingly it would work if I would make an action with the timer, for example getting an html element and increase it's value.

Any idea?

thanks

Upvotes: 1

Views: 171

Answers (3)

Arun Sharma
Arun Sharma

Reputation: 517

//start timer with label
console.time("label");
doSomething();
//end timer and print to corresponding label
console.timeEnd("label");
function doSomething()
{
     alert("stackoverflow bye!");
}

In cases where you have to measure performance console.time() and console.timeEnd() is your friend.

console.time(string) starts timer console.timeEnd(string) ends timer and print in console

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You should be aware of event loops in javascript to understand why your code didn't work as expected. The rule number 1 of event loop is, functions which are gonna work in async manner would be pushed in callBack queue. And the other functions would be pushed into call stack. Once all the functions in call stack got executed then only the functions in callBack queue will be executed one by one. No matter how much waiting time you gave.

.
.
var myVar = setInterval(myTimer, 10); 
//myTimer will be put under a timer internally
//And will wait for 10 ms to enter into callBack queue
//Say this was happened in 1st millisecond
.
.
.
var prime = isPrime(x); 
//isPrime(x) will be pushed into call stack and executed immediately
//if there is no other function in the stack
//Say this was happened in 5th millisecond
.
.
.
clearInterval(myVar);
//clearInterval(myVar) will be pushed into call stack and executed immediately
//if there is no other function in the stack.
//And simultaneously kill the timer which was created internally.
//Say this was happened in 7th millisecond
.
.
console.log(counter);
//Now, there was not at all a single chance to call the function myTimer.
//So the counter variable wouldn't be incremented.
//Thus it prints 0.

To do a proper instrumentation, you have to use the date object.

function isPrime(num){}

var prime, startTime, endTime;

startTime = Date.now();
prime = isPrime(x);
endTime = Date.now();

console.log(endTime - startTime, "ms taken to finish execution");

Upvotes: 1

HolgerT
HolgerT

Reputation: 62

I can't exactly understand you're target. If you want to check how fast youre methods are set a timestamp, run the method and waiting for a callback. If its arrived set a new timestamp and compare both.

Upvotes: 0

Related Questions