问题描述
当我使用 console.time
和 console.timeEnd
在 JavaScript 中测量函数或代码片段的执行速度时,它会将其打印到控制台:
timer: 14657.580078125 ms
如何将其四舍五入到最接近的整数或其他数字?我查看了这两个函数的文档,但都没有告诉我如何执行此操作。
解决方法
使用 Performance
API 会更好,因为 console
计时器不会以编程方式公开。
您可以使用 API 做几件事。您可以使用高分辨率时间戳:
let ts = performance.now();
//some code later
let measure = ts - performance.now();
这将为您提供 console
计时器的小数格式的时间(以毫秒为单位)。如果您在几秒钟内需要它,那么您也可以这样做:
console.log(Math.round(measure/1000));
Performance
api 有几种其他方法来标记时间戳并测量差异。 Take a look at it。
取自 MDN 的示例:
const markerNameA = "example-marker-a"
const markerNameB = "example-marker-b"
// Run some nested timeouts,and create a PerformanceMark for each.
performance.mark(markerNameA);
setTimeout(function() {
performance.mark(markerNameB);
setTimeout(function() {
// Create a variety of measurements.
performance.measure("measure a to b",markerNameA,markerNameB);
performance.measure("measure a to now",markerNameA);
performance.measure("measure from navigation start to b",undefined,markerNameB);
performance.measure("measure from navigation start to now");
// Pull out all of the measurements.
console.log(performance.getEntriesByType("measure"));
// Finally,clean up the entries.
performance.clearMarks();
performance.clearMeasures();
},1000);
},1000);
不幸的是,除了您已经在控制台中独占的输出之外,您不会让 console.time
和 console.timeEnd
(控制台对象的方法)执行任何操作.
也许 console.timeEnd
返回 undefined
而不是返回它放入控制台的相同持续时间太糟糕了。但是,即使它确实返回了那个持续时间,并且你设置了一个变量(并四舍五入),你的控制台仍然会在日志中显示那些未四舍五入的值。如果不对运行代码的每个 javascript 引擎进行黑客攻击,就无法改变这种行为,这是不切实际的。
对于四舍五入的值,您必须忘记 console.time
和 console.timeEnd
。那些不会有帮助。