Javascript 性能测试

本文介绍两种JavaScript性能测试方法:重复操作计时法与单位时间内完成次数法,详细解析每种方法的实现步骤与注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    第一种做法

        最常见的测试性能的做法,就是同一操作重复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引擎无法测量。

    第二种做法

        另一种思路是,测试单位时间内完成了多少次操作。

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;

        这种做法的注意之处在于,测试结构受外界环境影响很大,为了得到正确结构,必须重复多次。

转载于:https://my.oschina.net/u/1162572/blog/289099

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值