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

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


当前回答

由于console.time和performance.now在一些主要浏览器(如IE10)中不受支持,我创建了一个利用最佳可用方法的瘦实用程序。然而,它缺少错误用法的错误处理(在未初始化的计时器上调用End())。

使用它并根据您的需要进行改进。

Performance: {
    Timer: {},
    Start: function (name) {
        if (console && console.time) {
            console.time(name);
        } else if (window.performance.now) {
            this.Timer[name] = window.performance.now();
        } else {
            this.Timer[name] = new Date().getTime();
        }
    },
    End: function (name) {
        if (console && console.time) {
            console.timeEnd(name);
        } else {
            var result;
            if (window.performance.now) {
                result = window.performance.now() - this.Timer[name];
            } else {
                result = new Date().getTime() - this.Timer[name];
            }
            console.log(name + ": " + result);
        }
    }
}

其他回答

它可能会帮助你。

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文档

只能使用一个变量:

var timer = -performance.now();

// Do something

timer += performance.now();
console.log("Time: " + (timer/1000).toFixed(5) + " sec.")

timer/1000-将毫秒转换为秒

.toFixed(5)-修剪多余的数字

不要使用Date()。阅读以下内容。

使用performance.now():

<script>
var a = performance.now();
alert('do something...');
var b = performance.now();
alert('It took ' + (b - a) + ' ms.');
</script>

它适用于:

即10++火狐15++铬24++Safari 8++歌剧15++Android 4.4++等等

console.time对你来说可能可行,但它是非标准的§:

此功能是非标准的,不在标准轨道上。不要在面向Web的生产网站上使用它:它不会对每个用户都有效。实现之间也可能存在很大的不兼容性,并且行为可能会在未来发生变化。

除了浏览器支持之外,performance.now似乎有可能提供更准确的计时,因为它似乎是console.time的基本版本。


<rant>此外,不要将Date用于任何事情,因为它会受到“系统时间”变化的影响。这意味着当用户没有准确的系统时间时,我们将得到无效的结果,如“负计时”:

2014年10月,我的系统时钟失控了,猜猜怎么了。。。。我打开Gmail,看到我一天的所有电子邮件都是“0分钟前发送的”。我还以为Gmail应该是由谷歌的世界级工程师建造的。。。。。。。

(将你的系统时钟设置为一年前,然后转到Gmail,这样我们都可以开怀大笑。也许有一天,我们会为JS Date举办一个“耻辱大厅”。)

Google Spreadsheet的now()函数也存在此问题。

您将使用Date的唯一时间是您想向用户显示其系统时钟时间的时间。当你想得到时间或测量任何东西时,就不会这样。

由于console.time和performance.now在一些主要浏览器(如IE10)中不受支持,我创建了一个利用最佳可用方法的瘦实用程序。然而,它缺少错误用法的错误处理(在未初始化的计时器上调用End())。

使用它并根据您的需要进行改进。

Performance: {
    Timer: {},
    Start: function (name) {
        if (console && console.time) {
            console.time(name);
        } else if (window.performance.now) {
            this.Timer[name] = window.performance.now();
        } else {
            this.Timer[name] = new Date().getTime();
        }
    },
    End: function (name) {
        if (console && console.time) {
            console.timeEnd(name);
        } else {
            var result;
            if (window.performance.now) {
                result = window.performance.now() - this.Timer[name];
            } else {
                result = new Date().getTime() - this.Timer[name];
            }
            console.log(name + ": " + result);
        }
    }
}