简体   繁体   English

javascript执行时间各不相同

[英]javascript execution time varies

Am trying to figure out the best way to capture time executed by a statement. 我试图找出捕获语句执行时间的最佳方法。 For example what is the time taken by js stmt such as if(txt =='abc'). 例如,js stmt花费的时间是多少,例如if(txt =='abc')。 If i use console.time('test')/console.endTime('test') pair to calculate or simple js code (given below) to calculate time the console output varies every time code is executed. 如果我使用console.time('test')/ console.endTime('test')对来计算,或者使用简单的js代码(如下所示)来计算时间,则每次执行代码时控制台输出都会变化。

Also difference seen on console sometimes 1 digit, 2 digit to 3 digit in milliseconds ie sometime 1 ms, 60ms & sometimes 800ms that too order is inconsistent. 在控制台上看到的差异有时也以毫秒为单位在1位数,2位数到3位数之间,即有时1 ms,60ms有时是800ms,这也是顺序不一致的。 I even tried to run only once & close the browser & again run it so that other GC & variables does not come in picture to hamper the times but the result is same. 我什至尝试只运行一次,然后关闭浏览器,然后再次运行它,以使其他GC和变量不会出现在画面上,以免影响时间,但结果是相同的。 few ms is undestandle but such huge difference is lot to get clear time taken. 几毫秒是令人难以理解的,但如此巨大的差异对于获得清晰的时间而言是很大的。 So what exactly is best & consistent way to get time executed by interpreter. 那么,什么是最好的,一致的方法来让口译员执行时间呢? How can we find best yardstick to prove which stmt performs better when written in certain way or best to use 我们如何找到最佳标准来证明以某种方式编写或最好使用的stmt效果更好

var start = (new Date).getMilliseconds();
if(txt =='abc'){};
var diff = (new Date).getMilliseconds() - start;
console.log(diff);

* All test are conducted in FF. * 所有测试均在FF中进行。 Also different approach such getMilliseconds, getTime & console.endTime as taken one after other * 另一种不同的方法,例如getMilliseconds,getTime和console.endTime接二连三*

Erm.. you're using two very different functions to retrieve current timestamps. 嗯..您正在使用两个非常不同的函数来检索当前时间戳。

Date.prototype.getMilliseconds()

returns another (shorter) number than 返回比另一个(短)的数字

Date.prototype.getTime()

So that is not a good idea in general and is most likely the reason for your problems. 因此,通常这不是一个好主意,很可能是造成问题的原因。 If you want to measure in-code, you should always go with .getTime() or, better, Date.now() . 如果要测量代码中的内容,则应始终使用.getTime()或更好的Date.now() Both return a full timestamp number. 两者都返回完整的时间戳号。

The point here is that time to execute this instruction is in most cases much less than 0ms, so I don't understand why are you getting those differences. 这里的要点是,在大多数情况下,执行该指令的时间少于0ms,所以我不明白为什么会得到这些差异。 If I run on my machine: 如果我在计算机上运行:

for (x = 0; x < 100; x++) {                       
    var start = (new Date).getMilliseconds();
    if(txt =='abc'){};
    var diff = (new Date).getMilliseconds() - start;
    print(diff);
}

I get: 我得到:

0
0
0
0
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM