[英]How can I avoid "optimizing away" my javascript test cases?
I have a jsperf test case , and the result are pretty confusing.我有一个jsperf 测试用例,结果非常令人困惑。 I have three "snippets":
我有三个“片段”:
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;
我猜测 JS JIT 编译器会在我的“不必要”指令似乎没有任何效果时删除它们; so I started accumulating the results, and logging them to the console when the test loop is done, eg
所以我开始累积结果,并在测试循环完成后将它们记录到控制台,例如
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.
控制台日志记录的放缓似乎压倒了任何其他性能问题。
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.
或者jsperf坏了。
There are related questions already answered, but none that I've found specific to Javascript benchmarking.已经回答了相关问题,但我发现没有一个是针对 Javascript 基准测试的。
Don't put console.log
s in your timed sections.不要把
console.log
放在你的定时部分。 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.当然,这仍然不一定能防止循环不变代码运动,因此您还需要确保您的定时代码始终对不同的数据进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.