我需要以毫秒为单位获取执行时间。
我最初问这个问题是在2008年。当时接受的答案是使用newDate().getTime()。然而,我们现在都可以同意使用标准performance.now()API更合适。因此,我将接受的答案改为这个答案。
我需要以毫秒为单位获取执行时间。
我最初问这个问题是在2008年。当时接受的答案是使用newDate().getTime()。然而,我们现在都可以同意使用标准performance.now()API更合适。因此,我将接受的答案改为这个答案。
当前回答
最好的方法是使用性能挂钩模块。虽然不稳定,但您可以标记代码的特定区域,并测量标记区域之间的持续时间。
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);
在此处尝试
其他回答
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。
使用new Date().getTime()
getTime()方法返回自1970年1月1日午夜以来的毫秒数。
ex.
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);
在函数之前使用console.time(“此处的某个标签”),在函数之后使用console.timeEnd(“此处某个标签)。它将为您提供函数的运行时间。
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。
return Singleton.getInstance().initTime(标签);//返回时间init
return Singleton.getInstance().endTime(标签);//返回初始化和结束之间的总时间
支持标记的基本TypeScript示例。调用start(“something”)将启动计时器,而stop(“somehing”)将结束计时器,并返回包含已用时间的格式化字符串。
查看车队示例
/**
* 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`;
};
示例代码是导出每个函数。您可以将其放置到项目中,并从默认的import调用相应的方法,例如:
import * as time from './timer.js'
time.start('foo')
// do something
console.log('elapsed time: ' + time.stop('bar'))