switch语句比for循环更快吗?

时间:2015-08-07 13:11:42

标签: c performance for-loop optimization switch-statement

我正在查看Lourakis& amp;的稀疏束调整库(sba)的源代码。 Argyros。更确切地说,我正在查看以下函数nrmL2xmy,它计算两个向量的平方L2差。从行sba_levmar.c开始,从文件146复制以下代码:

/* Compute e=x-y for two n-vectors x and y and return the squared L2 norm of e.
 * e can coincide with either x or y. 
 * Uses loop unrolling and blocking to reduce bookkeeping overhead & pipeline
 * stalls and increase instruction-level parallelism; see http://www.abarnett.demon.co.uk/tutorial.html
 */
static double nrmL2xmy(double *const e, const double *const x, const double *const y, const int n)
{
const int blocksize=8, bpwr=3; /* 8=2^3 */
register int i;
int j1, j2, j3, j4, j5, j6, j7;
int blockn;
register double sum0=0.0, sum1=0.0, sum2=0.0, sum3=0.0;

  /* n may not be divisible by blocksize, 
   * go as near as we can first, then tidy up.
   */
  blockn = (n>>bpwr)<<bpwr; /* (n / blocksize) * blocksize; */

  /* unroll the loop in blocks of `blocksize'; looping downwards gains some more speed */
  for(i=blockn-1; i>0; i-=blocksize){
            e[i ]=x[i ]-y[i ]; sum0+=e[i ]*e[i ];
    j1=i-1; e[j1]=x[j1]-y[j1]; sum1+=e[j1]*e[j1];
    j2=i-2; e[j2]=x[j2]-y[j2]; sum2+=e[j2]*e[j2];
    j3=i-3; e[j3]=x[j3]-y[j3]; sum3+=e[j3]*e[j3];
    j4=i-4; e[j4]=x[j4]-y[j4]; sum0+=e[j4]*e[j4];
    j5=i-5; e[j5]=x[j5]-y[j5]; sum1+=e[j5]*e[j5];
    j6=i-6; e[j6]=x[j6]-y[j6]; sum2+=e[j6]*e[j6];
    j7=i-7; e[j7]=x[j7]-y[j7]; sum3+=e[j7]*e[j7];
  }

  /*
   * There may be some left to do.
   * This could be done as a simple for() loop, 
   * but a switch is faster (and more interesting) 
   */

  i=blockn;
  if(i<n){ 
  /* Jump into the case at the place that will allow
   * us to finish off the appropriate number of items. 
   */
    switch(n - i){ 
      case 7 : e[i]=x[i]-y[i]; sum0+=e[i]*e[i]; ++i;
      case 6 : e[i]=x[i]-y[i]; sum0+=e[i]*e[i]; ++i;
      case 5 : e[i]=x[i]-y[i]; sum0+=e[i]*e[i]; ++i;
      case 4 : e[i]=x[i]-y[i]; sum0+=e[i]*e[i]; ++i;
      case 3 : e[i]=x[i]-y[i]; sum0+=e[i]*e[i]; ++i;
      case 2 : e[i]=x[i]-y[i]; sum0+=e[i]*e[i]; ++i;
      case 1 : e[i]=x[i]-y[i]; sum0+=e[i]*e[i]; ++i;
    }
  }

  return sum0+sum1+sum2+sum3;
}

在代码中间(粗略地),作者陈述如下:

 /*
   * There may be some left to do.
   * This could be done as a simple for() loop, 
   * but a switch is faster (and more interesting) 
   */

我不明白为什么switch比简单for循环更快。

所以我的问题是:这句话是真的吗?如果是,为什么

3 个答案:

答案 0 :(得分:5)

有问题的switch案例在所有情况下都使用了fall-through,所以它基本上是一个展开的for循环。这很可能(稍微)更快,因为没有执行比较操作。

鉴于案例数量较少,任何性能差异都可以忽略不计,因此从代码可读性的角度来看,for循环会更好。

答案 1 :(得分:4)

在这种情况下,开关速度更快,因为循环会多次检查结束条件,而开关只会检查一次。这称为loop unrolling,优化编译器主要是自己完成。

答案 2 :(得分:0)

示例:只有在值匹配时才能生成输出。当年龄为18岁或年龄为60岁时。没有基于大于或小于的数据的联合数据。基于相等性比较数据。

For循环:检查数据的值是否小于或大于。 (在范围内)。 例如:可以告诉天气输入年龄超过18岁且小于60岁。

Switch Case:检查预先指定的数据的值。只等于。

根据你的说法,我会选择for循环。