加速循环中的函数调用 [英] Speed up function call inside loop

查看:145
本文介绍了加速循环中的函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

loop over a very long container (millions elements)
{
   each element compute 8 integers:  k1,k2,k3,...,k8

   call function    func(k1,k2,k3,...,k8)
}

container is a std::vector, element is a long integer
each k can only take {0,1,2,..5} six values.
func is a simple expression of complex number calculation, 
  involves std::conj and std::exp

为了加快速度,我将func的所有可能结果缓存到数组,并调用func_array [k1] [k2] [k3] ...。
但是如果简单地定义func_array为:
std :: complex func_array [6] [6] [6] ...,
程序在堆栈溢出时结束。

To speed up, I cache all possible outcome of 'func' to an array, and call func_array[k1][k2][k3]... instead. But if simply define func_array as: std::complex func_array[6][6][6]..., the program dies on stack overflow.

任何更好的解决方案以加快速度?

Any better solutions to speed up?

推荐答案

c $ c> std :: complex [6] [6] ... [6] 首先,这很容易导致堆栈溢出:这是
一个相当大的数组对于许多堆栈。第二:如果你在栈上创建
它,每次你调用
函数时,它将被重新初始化。你可能想要的是一个局部静态数组,
将被初始化一次(遇到第一次),然后
在函数调用之间保留它的值。

You're creating an array of std::complex[6][6]...[6] on the stack? First, this could easily cause stack overflow: that's a fairly large array for many stacks. And second: if you create it on the stack, it will be reinitialized each time you call the function. What you probably want is a local static array, which will be initialized once (the first time it is encountered), and then retain its value between function calls.

这篇关于加速循环中的函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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