Javascript 性能测试

    第一种作法性能

        最多见的测试性能的作法,就是同一操做重复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

相关文章
相关标签/搜索