How to get the output from console.timeEnd() in JS Console?

Deadly 提交于 2019-12-03 05:26:07

问题


I'd like to be able to get the string returned from console.timeEnd('t') in my Google Chrome Javascript Console.

In this example below, I'd like one variable which would contain "t: 0.276ms"

> console.time('t'); console.timeEnd('t');
  t: 0.276ms
< undefined

Is this something doable?


回答1:


In Google Chrome 23.0.1262.2 (Official Build 155904) dev, it looks like it's impossible. The only way I found to be able to calculate time with accuracy is to use window.performance.webkitNow()

Here's a simple example:

var start = window.performance.now();
...
var end = window.performance.now();
var time = end - start;

Read more at http://updates.html5rocks.com/2012/08/When-milliseconds-are-not-enough-performance-now




回答2:


simply you can use

var begin=Date.now();
something here ...;
var end= Date.now();

var timeSpent=(end-begin)/1000+"secs";

this is the simplest way and it will work on any browser not in only chrome




回答3:


Small helper to do some time measuring. timerEnd returns the time in ms, also the timers object contains information about how many times the timer with this name was used, the sum of all measured times and the average of the measurements. I find this quite useful, since the measured time for an operation depends on many factors, so it's best to measure it several times and look at the average.

var timers = {};
function timer(name) {
    timers[name + '_start'] = window.performance.now();
}

function timerEnd(name) {
    if (!timers[name + '_start']) return undefined;
    var time = window.performance.now() - timers[name + '_start'];
    var amount = timers[name + '_amount'] = timers[name + '_amount'] ? timers[name + '_amount'] + 1 : 1;
    var sum = timers[name + '_sum'] = timers[name + '_sum'] ? timers[name + '_sum'] + time : time;
    timers[name + '_avg'] = sum / amount;
    delete timers[name + '_start'];
    return time;
}



回答4:


console.timeEnd() function puts the time to console, and returns the value so you can save it to variable

var c = console.timeEnd('a');
c/1000+'s';

or you can save this variable to window object for latest usage

window.c = console.timeEnd('b');
window.c


来源:https://stackoverflow.com/questions/12492979/how-to-get-the-output-from-console-timeend-in-js-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!