我需要以毫秒为单位获取执行时间。
我最初在 2008 年问过这个问题。当时接受的答案是使用
new Date().getTime()
但是,我们现在都同意使用标准performance.now()
API 更合适。因此,我正在将接受的答案更改为这个答案。
我需要以毫秒为单位获取执行时间。
我最初在 2008 年问过这个问题。当时接受的答案是使用
new Date().getTime()
但是,我们现在都同意使用标准performance.now()
API 更合适。因此,我正在将接受的答案更改为这个答案。
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
它需要导入performance
类
进口业绩
const { performance } = require('perf_hooks');
console.time('doSomething')
doSomething() // <---- The function you're measuring time for
console.timeEnd('doSomething')
注意:
传递给time()
andtimeEnd()
方法的字符串必须匹配
(定时器才能按预期完成)。
console.time()
文件:
getTime() 方法返回自 1970 年 1 月 1 日午夜以来的毫秒数。
前任。
var start = new Date().getTime();
for (i = 0; i < 50000; ++i) {
// do something
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
<script>
var a = performance.now();
alert('do something...');
var b = performance.now();
alert('It took ' + (b - a) + ' ms.');
</script>
它适用于:
IE 10++
火狐 15++
铬 24 ++
野生动物园 8 ++
歌剧 15 ++
安卓 4.4++
console.time
对你来说可能是可行的,但它是非标准的§:
此功能是非标准的,不在标准轨道上。不要在面向 Web 的生产站点上使用它:它不适用于每个用户。实现之间也可能存在很大的不兼容性,并且行为可能会在未来发生变化。
除了浏览器支持之外,它performance.now
似乎有可能提供更准确的计时,因为它似乎是console.time
.
<rant> 另外,永远不要使用Date
任何东西,因为它会受到“系统时间”变化的影响。这意味着当用户没有准确的系统时间时,我们将得到无效的结果——比如“负计时”:
2014 年 10 月,我的系统时钟失控了,猜猜怎么着……我打开 Gmail,看到我一天的所有电子邮件“ 0 分钟前发送”。我还以为 Gmail 应该是由 Google 的世界级工程师打造的......
(将您的系统时钟设置为一年前,然后转到 Gmail,这样我们都可以开怀大笑。也许有一天我们会有一个JS的耻辱堂Date
。)
Google Spreadsheet 的now()
功能也存在这个问题。
您将使用的唯一时间Date
是您想向用户显示他的系统时钟时间。不是当你想获得时间或测量任何东西时。
如果您需要在本地开发机器上获取函数执行时间,您可以使用浏览器的分析工具或控制台命令,例如console.time()
和console.timeEnd()
。
所有现代浏览器都内置了 JavaScript 分析器。这些分析器应该提供最准确的测量结果,因为您不必修改现有代码,这可能会影响函数的执行时间。
要分析您的 JavaScript:
或者,在您的开发机器上console.time()
,您可以使用和将检测添加到您的代码中console.timeEnd()
。Firefox11+、Chrome2+ 和 IE11+ 支持这些功能,报告您通过console.time()
. time()
将用户定义的计时器名称作为参数,timeEnd()
然后报告自计时器启动以来的执行时间:
function a() {
console.time("mytimer");
... do stuff ...
var dur = console.timeEnd("myTimer"); // NOTE: dur only works in FF
}
请注意,只有 Firefox 在timeEnd()
调用中返回经过的时间。其他浏览器只是将结果报告给开发者控制台:返回值timeEnd()
是未定义的。
如果你想在野外获得函数执行时间,你将不得不检测你的代码。你有几个选择。您可以通过查询简单地保存开始和结束时间new Date().getTime()
:
function a() {
var start = new Date().getTime();
... do stuff ...
var end = new Date().getTime();
var dur = end - start;
}
但是,该Date
对象只有毫秒分辨率,并且会受到任何操作系统的系统时钟变化的影响。在现代浏览器中,有更好的选择。
更好的选择是使用高分辨率时间,也就是window.performance.now()
。 在两个重要方面now()
优于传统:Date.getTime()
now()
是具有亚毫秒分辨率的双精度数,表示自页面导航开始以来的毫秒数。它以小数形式返回微秒数(例如,1000.123 的值是 1 秒和 123 微秒)。
now()
是单调递增的。这很重要,因为在后续调用Date.getTime()
中可能会向前甚至向后跳跃。值得注意的是,如果操作系统的系统时间被更新(例如原子钟同步),Date.getTime()
也会被更新。 now()
保证总是单调递增的,所以它不受操作系统系统时间的影响——它总是挂钟时间(假设你的挂钟不是原子的……)。
now()
几乎可以在所有new Date().getTime()
, + new Date
andtDate.now()
的地方使用。例外是Date
和now()
时间不会混合,因为Date
它基于unix-epoch(自 1970 年以来的毫秒数),而now()
自页面导航开始以来的毫秒数(因此它将比 小得多Date
)。
这是一个如何使用的示例now()
:
function a() {
var start = window.performance.now();
... do stuff ...
var end = window.performance.now();
var dur = end - start;
}
now()
在 Chrome stable、Firefox 15+ 和 IE10 中受支持。还有几个polyfills可用。
在野外测量执行时间的另一种选择是UserTiming。UserTiming 的行为与console.time()
and类似console.timeEnd()
,但它使用与使用相同的高分辨率时间戳now()
(因此您可以获得亚毫秒单调递增的时钟),并将时间戳和持续时间保存到PerformanceTimeline。
UserTiming 具有标记(时间戳)和度量(持续时间)的概念。您可以根据需要定义任意多个,它们会在PerformanceTimeline上公开。
要保存时间戳,请调用mark(startMarkName)
. 要获得自第一次标记以来的持续时间,您只需调用measure(measurename, startMarkname)
. 然后,持续时间与您的标记一起保存在 PerformanceTimeline 中。
function a() {
window.performance.mark("start");
... do stuff ...
window.performance.measure("myfunctionduration", "start");
}
// duration is window.performance.getEntriesByName("myfunctionduration", "measure")[0];
UserTiming 在 IE10+ 和 Chrome25+ 中可用。还有一个polyfill可用(我写的)。
要获得精确值,您应该使用Performance interface。现代版本的 Firefox、Chrome、Opera 和 IE 都支持它。这是如何使用它的示例:
var performance = window.performance;
var t0 = performance.now();
doWork();
var t1 = performance.now();
console.log("Call to doWork took " + (t1 - t0) + " milliseconds.")
Date.getTime()
或者console.time()
不适合测量精确的执行时间。如果快速粗略估计适合您,您可以使用它们。通过粗略估计,我的意思是您可以从实时获得 15-60 毫秒的偏移。
查看这篇关于在 JavaScript 中测量执行时间的精彩文章。作者还给出了几个关于 JavaScript 时间准确性的链接,值得一读。
使用 Firebug,同时启用 Console 和 Javascript。单击配置文件。重新加载。再次单击配置文件。查看报告。
一个简单的解决方案,您也可以在这里使用 add 运算符
var start = +new Date();
callYourFunctionHere();
var end = +new Date();
var time = end - start;
console.log('total execution time = '+ time + 'ms');
process.hrtime() 在Node.js中可用- 它以纳秒为单位返回一个值
var hrTime = process.hrtime()
console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)
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()是可选的 - 只需将 false 传递给 StopWatch 构造函数。
可以只使用一个变量:
var timer = -performance.now();
// Do something
timer += performance.now();
console.log("Time: " + (timer/1000).toFixed(5) + " sec.")
timer/1000
- 将毫秒转换为秒
.toFixed(5)
- 修剪多余的数字
要进一步扩展 vsync 的代码以能够在 NodeJS 中将 timeEnd 作为值返回,请使用这段代码。
console.timeEndValue = function(label) { // Add console.timeEndValue, to add a return value
var time = this._times[label];
if (!time) {
throw new Error('No such label: ' + label);
}
var duration = Date.now() - time;
return duration;
};
现在像这样使用代码:
console.time('someFunction timer');
someFunction();
var executionTime = console.timeEndValue('someFunction timer');
console.log("The execution time is " + executionTime);
这给了你更多的可能性。您可以存储执行时间以用于更多目的,例如在方程式中使用它,或存储在数据库中,通过 websockets 发送到远程客户端,在网页上提供服务等。
这是计时功能的装饰器
它包装了函数,以便它们每次运行时都会计时
let timed = (f) => (...args) => {
let start = performance.now();
let ret = f(...args);
console.log(`function ${f.name} took ${(performance.now() - start).toFixed(3)}ms`);
return ret;
}
用法:
let test = () => { /* does something */ }
test = timed(test) // turns the function into a timed function in one line
test() // run your code as normal, logs 'function test took 1001.900ms'
如果您使用的是异步函数,则可以进行timed
异步并在 f(...args) 之前添加一个await
,这应该适用于这些函数。如果您希望一个装饰器同时处理同步和异步功能,它会变得更加复杂。
有多种方法可以实现这一目标:
使用控制台时间
console.time('function');
//run the function in between these two lines for that you need to
//measure time taken by the function. ("ex. function();")
console.timeEnd('function');
这是最有效的方法: 使用 performance.now(),例如
var v1 = performance.now();
//run the function here for which you have top measure the time
var v2 = performance.now();
console.log("total time taken = "+(v2-v1)+"milliseconds");
使用 +(add operator) 或 getTime()
var h2 = +new Date(); //or
var h2 = new Date().getTime();
for(i=0;i<500;i++) { /* do something */}
var h3 = +new Date(); //or
var h3 = new Date().getTime();
var timeTaken = h3-h2;
console.log("time ====", timeTaken);
将一元加号运算符应用于 Date 实例时会发生以下情况: 获取相关 Date 实例的值 将其转换为数字
注意:getTime()
提供比一元 + 运算符更好的性能。
它可能会帮助你。
var t0 = date.now();
doSomething();
var t1 = date.now();
console.log("Call to doSomething took approximate" + (t1 - t0)/1000 + " seconds.")
由于某些主要浏览器(即 IE10)不支持console.time
并且performance.now
不受支持,因此我创建了一个使用最佳可用方法的超薄实用程序。但是,它缺乏对错误用法的错误处理(调用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);
}
}
}
这是一个定时器功能。如果要测量未嵌套的多个事物之间的时间:
function timer(lap){
if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`);
timer.prev = performance.now();
}
类似于console.time()
,但如果您不需要跟踪以前的计时器,则更易于使用。
用法:
timer() // set the start
// do something
timer('built') // logs 'built in: 591.815ms'
// do something
timer('copied') // logs 'copied in: 0.065ms'
// do something
timer('compared') // logs 'compared in: 36.41ms'
如果你喜欢蓝色console.time()
,你可以用这条线代替
console.log(`${lap} in: %c${(performance.now()-timer.prev).toFixed(3)}ms`, 'color:blue');
几个月前,我整理了自己的例程,使用 Date.now() 对函数计时——即使当时接受的方法似乎是 performance.now()——因为性能对象尚不可用(已构建-in) 在稳定的 Node.js 版本中。
今天我做了更多的研究,发现了另一种计时方法。由于我还发现了如何在 Node.js 代码中使用它,所以我想在这里分享一下。
function functionTimer() {
performance.mark('start')
functionToBeTimed()
performance.mark('end')
performance.measure('Start to End', 'start', 'end')
const measure = performance.getEntriesByName('Start to End')[0]
console.log(measure.duration)
}
笔记:
如果您打算performance
在 Node.js 应用程序中使用该对象,则必须包含以下要求:
const { performance } = require('perf_hooks')
谢谢,Achim Koellner,将扩大您的答案:
var t0 = process.hrtime();
//Start of code to measure
//End of code
var timeInMilliseconds = process.hrtime(t0)[1]/1000000; // dividing by 1000000 gives milliseconds from nanoseconds
请注意,除了要测量的内容之外,您不应该做任何事情(例如,console.log
执行也需要时间并且会影响性能测试)。
请注意,为了衡量异步函数的执行时间,您应该var timeInMilliseconds = process.hrtime(t0)[1]/1000000;
在回调中插入。例如,
var t0 = process.hrtime();
someAsyncFunction(function(err, results) {
var timeInMilliseconds = process.hrtime(t0)[1]/1000000;
});
console.time('some label here')
在函数之前和函数之后使用console.timeEnd('some label here')
。它会给你函数的运行时间。
与服务器和客户端(节点或 DOM)一起使用,使用Performance
API。当您有许多小循环时很好,例如在一个调用 1000 次的函数中处理 1000 个数据对象,但您想查看此函数中的每个操作如何加起来总计。
所以这个使用了一个模块全局(单例)定时器。与类单例模式相同,只是使用起来更简单一些,但您需要将其放在单独的 egstopwatch.js
文件中。
const perf = typeof performance !== "undefined" ? performance : require('perf_hooks').performance;
const DIGITS = 2;
let _timers = {};
const _log = (label, delta?) => {
if (_timers[label]) {
console.log(`${label}: ` + (delta ? `${delta.toFixed(DIGITS)} ms last, ` : '') +
`${_timers[label].total.toFixed(DIGITS)} ms total, ${_timers[label].cycles} cycles`);
}
};
export const Stopwatch = {
start(label) {
const now = perf.now();
if (_timers[label]) {
if (!_timers[label].started) {
_timers[label].started = now;
}
} else {
_timers[label] = {
started: now,
total: 0,
cycles: 0
};
}
},
/** Returns total elapsed milliseconds, or null if stopwatch doesn't exist. */
stop(label, log = false) {
const now = perf.now();
if (_timers[label]) {
let delta;
if(_timers[label].started) {
delta = now - _timers[label].started;
_timers[label].started = null;
_timers[label].total += delta;
_timers[label].cycles++;
}
log && _log(label, delta);
return _timers[label].total;
} else {
return null;
}
},
/** Logs total time */
log: _log,
delete(label) {
delete _timers[label];
}
};
最好的方法是使用该performance hooks
模块。虽然不稳定,但您可以在代码的mark
特定区域和标记区域之间进行标记。measure
duration
const { performance, PerformanceObserver } = require('perf_hooks');
const measures = []
const obs = new PerformanceObserver(list => measures.push(...list.getEntries()));
obs.observe({ entryTypes: ['measure'] });
const getEntriesByType = cb => cb(measures);
const doSomething = val => {
performance.mark('beginning of the process');
val *= 2;
performance.mark('after multiplication');
performance.measure('time taken', 'beginning of the process', 'after multiplication');
getEntriesByType(entries => {
entries.forEach(entry => console.log(entry));
})
return val;
}
doSomething(4);
在这里试试
有性能
NodeJs:需要导入性能类
var time0 = performance.now(); // Store the time at this point into time0
yourFunction(); // The function you're measuring time for
var time1 = performance.now(); // Store the time at this point into time1
console.log("youFunction took " + (time1 - time0) + " milliseconds to execute");
使用控制台时间
console.time('someFunction');
someFunction(); // Whatever is timed goes between the two "console.time"
console.timeEnd('someFunction');
export default class Singleton {
static myInstance: Singleton = null;
_timers: any = {};
/**
* @returns {Singleton}
*/
static getInstance() {
if (Singleton.myInstance == null) {
Singleton.myInstance = new Singleton();
}
return this.myInstance;
}
initTime(label: string) {
this._timers[label] = Date.now();
return this._timers[label];
}
endTime(label: string) {
const endTime = Date.now();
if (this._timers[label]) {
const delta = endTime - this._timers[label];
const finalTime = `${label}: ${delta}ms`;
delete this._timers[label];
return finalTime;
} else {
return null;
}
}
}
InitTime 相关string
。
return Singleton.getInstance().initTime(label); // Returns the time init
return Singleton.getInstance().endTime(label); // Returns the total time between init and end
就我而言,我更喜欢使用@语法 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.time("myTimer");
console.timeLog("myTimer");
console.timeEnd("myTimer");
您可以在MDN和Node.js 文档中阅读更多相关信息。
适用于 Chrome、Firefox、Opera 和 NodeJS。(不在 Edge 或 Internet Explorer 上)。
使用此代码格式
const startTime =new Date().getTime();
//do something
const endTime = new Date().getTime();
console.log(`time taken ${(endTime - startTime)/1000} seconds`);
支持标记的基本 TypeScript 示例。调用start('something')
将启动计时器并stop('something')
结束计时器并返回包含经过时间的格式化字符串。
/**
* Mark entries
*/
export const marks: { [id: string]: number } = {};
/**
* Start timing
*/
export const start = (id: string) => {
return Object.assign(marks, {[id]: Date.now() })[id]
}
/**
* Clear all
*/
export const clear = () => {
for (const id in marks) delete marks[id];
};
/**
* Stop timing and return formatted elapsed time
*/
export const stop = (id: string) => {
const ms = Date.now() - marks[id];
delete marks[id];
return ms > 1000
? `${(ms / 1000).toFixed(0)}s ${+ms.toFixed(0).slice(1)}ms`
: `${ms.toFixed(0)}ms`;
};
示例代码正在导出每个函数。您可以将其放入项目中并从默认as
导入中相应地调用方法,例如:
import * as time from './timer.js'
time.start('foo')
// do something
console.log('elapsed time: ' + time.stop('bar'))
如前所述,检查并使用内置计时器。但是,如果您想或需要自己编写,这是我的两分钱:
//=-=|Source|=-=//
/**
* JavaScript Timer Object
*
* var now=timer['elapsed']();
* timer['stop']();
* timer['start']();
* timer['reset']();
*
* @expose
* @method timer
* @return {number}
*/
timer=function(){
var a=Date.now();
b=0;
return{
/** @expose */
elapsed:function(){return b=Date.now()-a},
start:function(){return a=Date.now()},
stop:function(){return Date.now()},
reset:function(){return a=0}
}
}();
//=-=|Google Advanced Optimized|=-=//
timer=function(){var a=Date.now();b=0;return{a:function(){return b=Date.now()-a},start:function(){return a=Date.now()},stop:function(){return Date.now()},reset:function(){return a=0}}}();
您还应该考虑阅读有关 bigO 表示法的信息。它可能比计时功能更好地了解正在发生的事情
接受的答案是错误的!
由于 JavaScript 是异步的,因此接受答案的变量 end 的值是错误的。
var start = new Date().getTime();
for (i = 0; i < 50000; ++i) {
// JavaScript is not waiting until the for is finished !!
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
for 的执行可能非常快,所以你看不到结果是错误的。您可以使用执行某些请求的代码对其进行测试:
var start = new Date().getTime();
for (i = 0; i < 50000; ++i) {
$.ajax({
url: 'www.oneOfYourWebsites.com',
success: function(){
console.log("success");
}
});
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
因此警报会很快提示,但在控制台中您会看到 ajax 请求仍在继续。
这是你应该怎么做的:https ://developer.mozilla.org/en-US/docs/Web/API/Performance.now