如何防止繁忙等待的优化 [英] How to prevent optimization of busy-wait

查看:75
本文介绍了如何防止繁忙等待的优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个函数busy-wait。

I need to have a function busy-wait.

for(long int j=0; j<50000000; ++j)
  ;

当我在发布模式下进行编译时,这一点得到了优化。除了在调试模式下进行编译以外,还有什么方法可以使它们得到优化?我并不特别在意循环的实际数量,但是它必须是一个明显的忙碌延迟。

When I compile in release mode, this gets optimized out. Other than compiling in debug mode, is there some way to cause this to not get optimized out? I don't particularly care about the actual number of the loop, but it must be a noticeable busy-delay.

推荐答案

我不知道为什么需要保持CPU繁忙,但让我们假设您确实有充分的理由,例如确保CPU保持繁忙,以至于不考虑发生的故障到上周,一切都很沮丧,但我离题了……

I don't know why you need to keep the CPU busy, but let's assume that you really have a good reason, like making sure you keep the CPU busy so it doesn't think about that breakup it went through last week and get all depressed but I digress...

您所看到的问题是编译器执行了死代码消除:它看到循环确实一无所有(即没有副作用),因此将其消除。因此,您可以使其具有副作用。

The problem you are seeing is that the compiler performs "dead code elimination": it sees that the loop does nothing (i.e. has no side-effects) and so cuts it out. So you could make it have a side-effect.

一个简单的解决方案是该功能:

A simple solution would be this function:

void busywait(long iterations)
{
    for(volatile long i = 0; i != iterations; i++)
        ;
}

通过标记 i 作为 volatile ,您要确保循环具有副作用,因为存储到易失性对象(即,我们执行的增量)被视为具有副作用。

By marking i as volatile you are ensuring that the loop has side-effects, since stores to volatile objects (i.e. the incrementing we perform) are treated as having side-effects.

这篇关于如何防止繁忙等待的优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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