0

I have a function which will be called many times throughout my code. This function updates 2 values(passed as argument) in an array. Since it is called too many times, I want this function optimized.

Yes I do have a simplest code to do that,

int global_array[MAX];
int * ptr_to_my_global_array = &global_array[0];

main()
{
  int a=0,b=0;

  my_func(a,b);
  a++;b++;
  my_func(a,b);
  a++;b++;
  my_func(a,b);
  a++;b++;
  my_func(a,b);
  a++;b++;
  my_func(a,b);
  a++;b++;
  //and so on
}

void my_func(int c,int d)
{

   *ptr_to_my_global_array = c;
   ptr_to_my_global_array++;
   *ptr_to_my_global_array = d;
   ptr_to_my_global_array++;

}

Please do not suggest any mem_copy,mem_set solutions. There may be no other solution, but was just curious if I could make this faster.

4

2 回答 2

2

使用宏而不是函数调用,这可能会减少调用函数的开销。但是,您可能会发现编译器优化已经这样做了。

基准测试和测试:-)

于 2012-07-16T13:06:54.913 回答
0

如果您正在测试不同的东西,您可以将其与以下内容进行比较:

inline void my_func(int c,int d)
{
ptr_to_my_global_array[0] = c;
ptr_to_my_global_array[1] = d;
ptr_to_my_global_array += 2;
}

优化器可能会将事情整理出来,以便两者之间没有区别,但您不妨看看它对发出的代码有什么区别(如果有的话)。

基本上,您的函数非常简单,以至于很难看出人类如何比优化器做得更好。因此,对您的程序的任何真正改进都需要在main而不是在my_func.

于 2012-07-16T13:25:58.733 回答