功能效率测量javascript

时间:2017-01-15 10:05:44

标签: javascript timer

我想检查我的功能的效率,让我们说找一个素数,我写了类似的东西:

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);

我的问题是counter = 0到底

有趣的是,如果我使用计时器进行操作,例如获取html元素并增加其值,它将起作用。

有什么想法吗?

感谢

3 个答案:

答案 0 :(得分:1)

您应该了解javascript中的事件循环,以了解您的代码无法按预期工作的原因。事件循环的规则1是,将以异步方式工作的函数将被推送到callBack队列中。其他函数将被推入调用堆栈。一旦调用堆栈中的所有函数都被执行,那么只有callBack队列中的函数将被逐个执行。无论你给了多少等待时间。

.
.
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.

要进行正确的检测,您必须使用日期对象。

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");

答案 1 :(得分:1)



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




如果你必须衡量性能console.time()和console.timeEnd()是你的朋友。

console.time(string)启动计时器 console.timeEnd(string)结束计时器并在控制台中打印

答案 2 :(得分:0)

我无法完全理解你的目标。如果要检查方法设置时间戳的速度,请运行方法并等待回调。如果它到达设置了一个新的时间戳并比较它们。