简体   繁体   English

最奇怪的优化? 在`libuv`中。 请解释

[英]Strange optimization? in `libuv`. Please explain

The libuv contains next code in core.c:uv_run() libuvcore.c:uv_run()包含下一个代码

/* The if statement lets the compiler compile it to a conditional store.
 * Avoids dirtying a cache line.
 */
if (loop->stop_flag != 0)
    loop->stop_flag = 0;

What does this mean? 这是什么意思? Is it some kind of optimization? 是某种优化吗? Why they did not simply assign 0? 为什么他们不简单地分配0?

Yes, just like the comment says. 是的,就像评论中所说的那样。 In case the flag is already 0, there is no need to write any data to the memory, thus avoiding a possible eviction of present data in the cache and replacing it with 0 for the flag. 如果该标志已经为0,则无需将任何数据写入内存,从而避免了可能将当前数据移出高速缓存并将该标志替换为0。 This will provide added value only in extremely time-critical applications. 仅在时间紧迫的应用中,这将提供附加值。

I would argue this optimization is bad. 我认为这种优化是不好的。 For example, on gcc with -O3 it gives following code: 例如,在带有-O3的gcc上,它给出以下代码:

foo():
        movl    stop_flag(%rip), %eax
        testl   %eax, %eax
        je      .L3
        movl    $0, stop_flag(%rip)
.L3:
        ret
stop_flag:
        .zero   4

As you see, there is no conditional move, but a branch. 如您所见,没有条件移动,而是分支。 And I am sure, branch misprediction is far worse than dirtying the cache line. 而且我敢肯定,分支错误预测远比弄脏缓存行还糟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM