简体   繁体   English

如何监视循环?

[英]How to monitor a for-loop?

I would like to monitor the content of a for loop every X millisecond: 我想每X毫秒监视一次for循环的内容:

Here is an example, I expect to see progression percentage every 0.1 seconds : 这是一个示例,我希望每0.1秒查看一次进度百分比:

for (i = 0, max = 9007199254740992, timer = setInterval(function() {console.log(100*i/max);}, 100); i < max; i++) {
  // something
}
clearInterval(timer);

But it does not output anything. 但是它不输出任何东西。

I would like not to add a test in my loop to avoid using useless computation time. 我不想在循环中添加测试,以避免浪费无用的计算时间。

Due to the single-threaded nature of Javascript, your setInterval() callback can't possibly be called before the end of the for loop, no matter how long it takes to execute. 由于Java setInterval()的单线程性质,无论执行多长时间,都不可能在for循环结束之前调用setInterval()回调。

I'd recommend to do it the other way around: log elapsed time every N iterations. 我建议采用另一种方法:每N次迭代记录经过的时间。

 var res = [], ts = performance.now(); for(var i = 0, max = 1E6; i < max; i++) { if(!(i % 10000)) { res.push(performance.now() - ts); } // do something } console.log(res); 

Or: 要么:

 var res = [], ts = performance.now(); for(var i = 0, iMax = 1E6; i < iMax; i += 10000) { for(var j = i, jMax = Math.min(i + 10000, iMax); j < jMax; j++) { // do something } res.push(performance.now() - ts); } console.log(res); 

If you really want to log in real time, you'd have to yield control to the browser after each batch of N iterations. 如果您确实想实时登录,则必须在每批N次迭代后将控制权交给浏览器。 Performance wise, this will probably have a significant impact, though. 在性能方面,这可能会产生重大影响。

 var res = [], ts = performance.now(); function processBatch(i, iMax, sz) { for(var j = i, jMax = Math.min(i + sz, iMax); j < jMax; j++) { // do something } console.log((j * 100 / iMax) + '%', (performance.now() - ts).toFixed(2) + 'ms'); if(j < iMax) { setTimeout(function() { processBatch(j, iMax, sz); }, 0); } } processBatch(0, 1E6, 10000); 

EDIT : This third method was significantly updated. 编辑 :这第三种方法进行了重大更新。 The previous version was erroneous. 以前的版本是错误的。

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

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