第一種作法性能
最多見的測試性能的作法,就是同一操做重複n次,而後計算每次操做的平均時間。測試
var totalTime, start = new Date, iterations = 6; while (iterations--) { // Code snippet goes here } // totalTime → the number of milliseconds it took to execute // the code snippet 6 times totalTime = new Date - start;
上面代碼的問題在於,因爲計算機的性能不斷提升,若是隻重複6次,極可能獲得0毫秒的結果,即不到1毫秒,Javascript引擎沒法測量。spa
第二種作法code
另外一種思路是,測試單位時間內完成了多少次操做。ip
var hz, period, startTime = new Date, runs = 0; do { // Code snippet goes here runs++; totalTime = new Date - startTime; } while (totalTime < 1000); // convert ms to seconds totalTime /= 1000; // period → how long per operation period = totalTime / runs; // hz → the number of operations per second hz = 1 / period; // can be shortened to // hz = (runs * 1000) / totalTime;
這種作法的注意之處在於,測試結構受外界環境影響很大,爲了獲得正確結構,必須重複屢次。it