如何避免“优化"?我的javascript测试用例? [英] How can I avoid "optimizing away" my javascript test cases?

查看:75
本文介绍了如何避免“优化"?我的javascript测试用例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 jsperf测试用例,结果令人困惑.我有三个摘要":

I have a jsperf test case, and the result are pretty confusing. I have three "snippets":

  • 乘法
  • 部门
  • 控制(两项操作均未完成)

在大多数情况下,它们的速度几乎相同,甚至控制也一样!我猜想JS JIT编译器删除了我的不必要的"指示,当它们似乎没有任何作用时;所以我开始累积结果,并在完成测试循环后将其记录到控制台,例如

and most of the time, they all come out about the same speed... even the control! I guessed that the JS JIT compiler was removing my "unnecessary" instructions when they didn't seem to have any effect; so I started accumulating the results, and logging them to the console when the test loop is done, e.g.

for (var i = 0; i < nNumbers; i++) {
  result += a[i] / b[i];
}
console.log(result);

但是,当控制台打开与未打开时​​,我得到了截然不同的结果.控制台日志记录的速度下降似乎淹没了其他所有性能问题.

But then, I got wildly differing results when the console was open from when it wasn't. The slowdown from the console logging seemed to overwhelm any other performance issues.

因此,我尝试提高每个代码段"中的迭代次数,以最大程度地减少与我要测试的操作有关的日志记录量.但是三个片段之间仍然没有明显的速度差异.的确,除法和乘法运算的速度与评估常数的速度大致相同?我一定做错了什么.否则jsperf损坏了.

So I tried cranking up the number of iterations within each "snippet," to minimize the amount of logging relative to the operations I'm trying to test. But I still get no significant speed difference between the three snippets. Really, division and multiplication are both about the same speed as evaluating a constant?? I must be doing something wrong. Or jsperf is broken.

已经回答了一些相关问题,但是我发现没有一个特定于Javascript基准测试.

There are related questions already answered, but none that I've found specific to Javascript benchmarking.

推荐答案

请勿在计时部分中放入 console.log .与您实际要测量的操作相比,它的运行速度极其慢,因此会使您的结果产生偏差.另外-您已经注意到-控制台打开与否的时间会有所不同.

Don't put console.logs in your timed sections. It's horribly slow in comparisons to the operations you actually want to measure, so it skews your results. Also - as you noticed - it varies in timing when the console is open or not.

您可以通过将结果放入全局数组来防止优化.优化程序只能删除不影响结果的代码,如果它操纵全局状态,则是不可能的.

You can prevent deoptimisations by putting your results in a global array. The optimiser can only remove code that does not affect the outcome, which is impossible if it manipulates global state.

当然,这仍然不一定会阻止循环不变代码运动,因此您还需要确保定时代码始终在不同的数据上运行.

Of course, this still does not necessarily prevent loop-invariant code motion, so you also need to make sure that your timed code always operates on different data.

这篇关于如何避免“优化"?我的javascript测试用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆