new Date().getTime() 方法返回自 1970 年 1 月 1 日午夜以来的毫秒数。
1 2 3 4 5 6 7
var start = newDate().getTime(); for (i = 0; i < 50000; ++i) { // do something } var end = newDate().getTime(); var time = end - start; alert('Execution time: ' + time);
StopWatch.prototype.getElapsedMilliseconds = function () { if (this.running) { this.stopTime = this.currentTime(); } returnthis.stopTime - this.startTime; };
StopWatch.prototype.getElapsedSeconds = function () { returnthis.getElapsedMilliseconds() / 1000; };
StopWatch.prototype.printElapsed = function (name) { var currentName = name || 'Elapsed:'; console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]'); };
// 使用示例 var stopwatch = newStopWatch(); stopwatch.start(); for (var index = 0; index < 100; index++) { stopwatch.printElapsed('Instance[' + index + ']'); } stopwatch.stop(); stopwatch.printElapsed();