函数效率度量javascript

函数效率度量javascript,javascript,timer,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

我想检查我的函数的效率,比如说找到一个素数,我写了如下内容:

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元素并增加它的值,它就会起作用

有什么想法吗


谢谢

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

.
.
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.
要进行正确的检测,必须使用date对象

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

我不太明白你是目标。如果要检查方法设置时间戳的速度,请运行该方法并等待回调。如果到达,则设置一个新的时间戳并比较两者。

//使用标签启动计时器
控制台。时间(“标签”);
doSomething();
//结束计时器并打印到相应的标签
控制台。时间结束(“标签”);
函数doSomething()
{
警报(“再见!”);
}