是否可以标记一个不优化的函数?

发布于 2025-02-11 13:15:22 字数 465 浏览 1 评论 0原文

给定一个没有副作用的(内联删除零零)函数f

inline void f() { /*...*/ }

可以编写调用f g g f g 代码>,但不会通过实施来优化:

inline void g() { [[dont_optimize_this_away ???]] f(); }

是否有某种方法可以告诉编译器“调用F并在inline inline中,但不要优化这些说明”?

我认为在标准C ++ 20中没有办法做到这一点。 (或者是吗?)

...但是是否有一种特定于平台的方法可以在x86-64上使用gccclang和/或msvc?某种仪器 /编译的内置 /属性?

Given a (inline void-returning nullary) function f that doesn't have side effects:

inline void f() { /*...*/ }

Is it possible to write an inline function g that calls f but won't be optimized out by the implementation:

inline void g() { [[dont_optimize_this_away ???]] f(); }

Is there some way to tell the compiler "call f and inline the assembly, but don't optimize those instructions away"?

I don't think there is a way to do this in standard C++20. (or is there?)

...but is there a platform-specific way to do it on x86-64 with gcc, clang and/or msvc ? Some kind of instrinsic / compile builtin / attribute?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

染火枫林 2025-02-18 13:15:22

根据 this
您可以使用__属性__((优化(“ O0”))) like:

inline void __attribute__((optimize("O0"))) g() { [[dont_optimize_this_away ???]] f(); }

According to this post,
you can use __attribute__((optimize("O0"))) like:

inline void __attribute__((optimize("O0"))) g() { [[dont_optimize_this_away ???]] f(); }
不打扰别人 2025-02-18 13:15:22

也许这个?查看释放的拆卸看起来仍然在那里。 (Windows Pragma: https:/ com/en-us/cpp/preprocessor/optimize?view = msvc-170

inline void f() {
    //std::cout << "I do a thing";
}

#pragma optimize( "", off ) 
inline void g() {
    f();
}
#pragma optimize( "", on )

int main()
{
    g();
}

Maybe this? Looking at the disassembly of release looks like it's still in there. (Windows pragma: https://learn.microsoft.com/en-us/cpp/preprocessor/optimize?view=msvc-170)

inline void f() {
    //std::cout << "I do a thing";
}

#pragma optimize( "", off ) 
inline void g() {
    f();
}
#pragma optimize( "", on )

int main()
{
    g();
}
长梦不多时 2025-02-18 13:15:22

有办法。例如,Google基准标有 benchmark“> benchmark”> benchmark :: donotoptimize

只需将其实现复制到您的代码中,并将其应用于您的的索引变量(int i = 0; i = 0; i&lt; i&i ++);表单>在问题下注释。

这是

There is a way. For example Google benchmark has benchmark::DoNotOptimize.

Just copy its implementation to your code and apply it for index variable for this dummy loop of yours for (int i = 0; i < 100; i++); form comment under a question.

Here is technical explanation how it works for gcc (note it is old source so name of function is different).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文