gpt4 book ai didi

c++ - 如何向编译器提示循环运行的最长时间

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:41:08 26 4
gpt4 key购买 nike

// if I know that in_x will never be bigger than Max
template <unsigned Max>
void foo(unsigned in_x)
{
unsigned cap = Max;

// I can tell the compiler this loop will never run more than log(Max) times
for (; cap != 0 && in_x != 0; cap >>= 1, in_x >>= 1)
{
}
}

如上代码所示,我的猜测是如果我直接写

对于 (; in_x != 0; in_x >>= 1)

编译器不会展开循环,因为它不能确定最大可能的 in_x。

我想知道我是对还是错,是否有更好的方法来处理这些事情。


或者也许问题可以概括为好像可以编写一些代码来告诉编译器某些运行时值的范围,并且这样的代码不一定被编译成运行时二进制文件。


真的,和编译器打架XD

// with MSC
// if no __forceinline here, unrolling is ok, but the function will not be inlined
// if I add __forceinline here, lol, the entire loop is unrolled (or should I say the tree is expanded)...
// compiler freezes when Max is something like 1024
template <int Max>
__forceinline void find(int **in_a, int in_size, int in_key)
{
if (in_size == 0)
{
return;
}

if (Max == 0)
{
return;
}

{
int m = in_size / 2;

if ((*in_a)[m] >= in_key)
{
find<Max / 2>(in_a, m, in_key);
}
else
{
*in_a = *in_a + m + 1;

find<Max - Max / 2 - 1>(in_a, in_size - (m + 1), in_key);
}
}
}

最佳答案

实现这种行为的正确方法是使用 TMP 自行解除循环。即使这样,您仍将依赖编译器协作来进行大量内联(这是授予的)。查看以下代码是否有帮助:

template <unsigned char MaxRec>
inline void foo(unsigned in_x)
{
if (MaxRec == 0) // will be eliminated at compile time
return; // tells the compiler to stop the pseudo recursion

if (in_x == 0) {
// TODO : end recursion;
return;
};

// TODO: Process for iteration rec

// Note: NOT recursion, the compiler would not be able to inline
foo<MaxRec-1>(in_x >> 1);
}

// Usage:
foo<5>(in_x); // doubt the compiler will inline 32 times, but you can try.

关于c++ - 如何向编译器提示循环运行的最长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9544601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com