一共有5中方法(執行效率依次降低)
Date.now();
new Date().getTime();
+new Date();
process.uptime();
process.hrtime();
解釋
Date.now()、new Date().getTime() 和 +new Date() 是瀏覽器環境下一直都有的,自然不必多說。
process.uptime() 返回的是Node程序已運行的時間,單位秒。
process.hrtime() 返回的是當前的高分辨率時間,格式為[秒, 納秒]。它是相對于在過去的任意時間,該值與日期無關。優點是:可以獲得一個非常精準的時間差,不會受到時鐘飄逸的影響;缺點是:速度慢。
結論
要獲取一個非常精確地時間間隔,用 process.hrtime();大量循環獲取時間戳的時候,要考慮性能,用 Date.now()。
監測性能的代碼
function getTimeDifference(method, time) {
var count = time || '100000';
console.time(method);
while (count) {
eval(method);
count--;
}
console.timeEnd(method);
}
getTimeDifference('Date.now()');
getTimeDifference('process.uptime()');
getTimeDifference('new Date().getTime()');
getTimeDifference('+ new Date()');
getTimeDifference('process.hrtime()');