我需要以毫秒为单位获取执行时间。

我最初问这个问题是在2008年。当时接受的答案是使用newDate().getTime()。然而,我们现在都可以同意使用标准performance.now()API更合适。因此,我将接受的答案改为这个答案。


当前回答

var StopWatch = function (performance) {
    this.startTime = 0;
    this.stopTime = 0;
    this.running = false;
    this.performance = performance === false ? false : !!window.performance;
};

StopWatch.prototype.currentTime = function () {
    return this.performance ? window.performance.now() : new Date().getTime();
};

StopWatch.prototype.start = function () {
    this.startTime = this.currentTime();
    this.running = true;
};

StopWatch.prototype.stop = function () {
    this.stopTime = this.currentTime();
    this.running = false;
};

StopWatch.prototype.getElapsedMilliseconds = function () {
    if (this.running) {
        this.stopTime = this.currentTime();
    }

    return this.stopTime - this.startTime;
};

StopWatch.prototype.getElapsedSeconds = function () {
    return this.getElapsedMilliseconds() / 1000;
};

StopWatch.prototype.printElapsed = function (name) {
    var currentName = name || 'Elapsed:';

    console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
};

基准

var stopwatch = new StopWatch();
stopwatch.start();

for (var index = 0; index < 100; index++) {
    stopwatch.printElapsed('Instance[' + index + ']');
}

stopwatch.stop();

stopwatch.printElapsed();

输出

Instance[0] [0ms] [0s]
Instance[1] [2.999999967869371ms] [0.002999999967869371s]
Instance[2] [2.999999967869371ms] [0.002999999967869371s]
/* ... */
Instance[99] [10.999999998603016ms] [0.010999999998603016s]
Elapsed: [10.999999998603016ms] [0.010999999998603016s]

performance.now()是可选的-只需向StopWatch构造函数传递false。

其他回答

在我的例子中,我更喜欢使用@grammar suger并用babel编译它。这种方法的问题是函数必须位于对象内部。

JS代码示例

function timer() {
    return (target, propertyKey, descriptor) => {
        const start = Date.now();
        let oldFunc = descriptor.value;

        descriptor.value = async function (){
            var result = await oldFunc.apply(this, arguments);
            console.log(Date.now() - start);
            return result;
        }
    }
}

// Util function 
function delay(timeout) {
    return new Promise((resolve) => setTimeout(() => {
        resolve();
    }, timeout));
}

class Test {
    @timer()
    async test(timout) {
        await delay(timout)
        console.log("delay 1");
        await delay(timout)
        console.log("delay 2");
    }
}

const t = new Test();
t.test(1000)
t.test(100)

babelrc(用于babel 6)

 {
    "plugins": [
        "transform-decorators-legacy"
    ]
 }

有多种方法可以实现这一目标:

使用console.timeconsole.time(“函数”);//在这两行之间运行函数//测量函数所用的时间。(“例如函数();”)console.timeEnd('功能');这是最有效的方法:使用performance.now(),例如。var v1=performance.now();//在这里运行您可以测量时间的函数var v2=性能.now();console.log(“总时间=”+(v2-v1)+“毫秒”);使用+(add运算符)或getTime()var h2=+新日期()//或var h2=新日期().getTime();对于(i=0;i<500;i++){/*做某事*/}var h3=+新日期()//或var h3=新日期().getTime();var timeTaken=h3-h2;console.log(“time===”,timeTaken);

以下是将一元加号运算符应用于Date实例时的情况:获取相关Date实例的值将其转换为数字

注意:getTime()比一元+运算符提供更好的性能。

它可能会帮助你。

var t0=date.now();做某事();var t1=date.now();console.log(“调用doSomething花费了大约”+(t1-t0)/1000+“秒”)

使用performance.now():

var startTime = performance.now()

doSomething()   // <---- measured code goes between startTime and endTime
    
var endTime = performance.now()

console.log(`Call to doSomething took ${endTime - startTime} milliseconds`)

在Node.js中,需要导入性能类

进口性能

const { performance } = require('perf_hooks');

使用console.time:(生活水平)

console.time('doSomething')
    
doSomething()   // <---- The function you're measuring time for 
    
console.timeEnd('doSomething')

注意:传递给time()和timeEnd()方法的字符串必须匹配(计时器才能按预期完成)。

console.time()文档:MDN文档Node.js文档

要启动计时器,请使用console.time(“myTimer”);可选:要打印经过的时间,请使用console.timeLog(“myTimer”);最后,停止计时器并打印最终结果time:console.timeEnd(“myTimer”);

您可以在MDN和Node.js文档中阅读更多关于这一点的信息。

可在Chrome、Firefox、Opera和NodeJS上使用。(不在Edge或Internet Explorer上)。