C的循环优化 [英] Loop optimization for C

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

问题描述

如何使用循环优化优化此代码?



我尝试过:



How do I optimize this code by using loop optimization?

What I have tried:

#include<stdio.h>
#include<omp.h>

void merge(int array[],int low,int mid,int high)
{
  int temp[30];
  int i,j,k,m; 
  j=low;
  m=mid+1;
  for(i=low; j<=mid && m<=high ; i++)
  {
     if(array[j]<=array[m])
     {
         temp[i]=array[j];
         j++;
     }
     else
     {
         temp[i]=array[m];
         m++;
     }
  }
  if(j>mid)
  {
     for(k=m; k<=high; k++)
     {
         temp[i]=array[k];
         i++;
     }
  }
  else
  {
     for(k=j; k<=mid; k++)
     {
        temp[i]=array[k];
        i++;
     }
  }
  for(k=low; k<=high; k++)
     array[k]=temp[k];
}


void mergesort(int array[],int low,int high)
{
 int mid;
 if(low<high)
 {
   mid=(low+high)/2;

   #pragma omp parallel sections num_threads(2) 
    {
      #pragma omp section
        {
          mergesort(array,low,mid);
        }
      
      #pragma omp section
        {
          mergesort(array,mid+1,high);
        }
    }
   merge(array,low,mid,high);
 }
}


int main()
{
 int array[50];
 int i,size;
 printf("Enter total no. of elements:\n");
 scanf("%d",&size);
 printf("Enter %d elements:\n",size);
 for(i=0; i<size; i++)
 {
   scanf("%d",&array[i]);
 }
 mergesort(array,0,size-1);
 printf("Sorted Elements as follows:\n");
 for(i=0; i<size; i++)
    printf("%d ",array[i]);
 printf("\n");
 return 0;
}

推荐答案

Quote:

我想结合循环优化和OpenMP,以减少执行时间。但我不确定可以使用哪种循环优化技术。例如loopfusion,循环交换,循环展开等等。

I want to combine loop optimization and OpenMP in order to reduce the execution time. But im not sure what kind of loop optimization technique that can be used. For example like loopfusion, loop interchanging, loop unrolling and etc.



我担心在这种情况下没有循环优化,因为每个循环都在 merge()并且每个操作必须按顺序完成,操作顺序取决于数据因此是不可预测的。


I fear there is no loop optimization in this case because each loop is in merge() and each operation must be done in sequence, the order of operation depend on data thus is inpredictable.


首先检查这个。

http://wiki.c2.com/?RulesOfOptimization [ ^ ]
Check this out first.
http://wiki.c2.com/?RulesOfOptimization[^]


这篇关于C的循环优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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