如今,计算机CPU通常是多核的,许多程序并未针对多核进行优化,因此无法充分利用cpu的性能。
例如,如果您在vs2010中编写了while(1)循环,则旧计算机上运行的CPU占100%,而新四核计算机上仅占25%。不可能更高。
许多地方都说使用openmp可以充分发挥多核处理的能力,但是在我向程序中添加了openmp优化指令后,我仍然无法达到100%的性能。也许我弄错了。
因此,我这里没有使用openmp,而是使用多线程来加速计算。
例如,如果要处理10000 * 10000像素的图像,则可以打开四个线程,每个线程分别处理2500 * 10000像素,因此速度可以提高4倍。

实验效果证明了上述方法的有效性,速度提高了近4倍。
当然,如果它具有8个内核或16个内核以及8个或16个线程,则基本上可以增加8倍或16倍。
图像算法通常很容易并行编写。我在这里使用了freeimage图片库,而CPU是i5 4590。
处理10000 * 10000图像时,单线程花费了3500ms,四线程花费了900ms,这基本上是4倍。
该程序也许可以打开更多线程,但是我还没有尝试过。

代码如下,功能是反转颜色:
#include#include #include #include #include "FreeImage.h" using namespace std;
//就设成全局变量吧 FREE_IMAGE_FORMAT fif; FIBITMAP *img; FIBITMAP *re;
int h; int w; int bpp; void Init() { string name="img.jpg"; fif=FreeImage_GetFileType(name.c_str()); img=FreeImage_Load(fif,name.c_str()); h=FreeImage_GetHeight(img); w=FreeImage_GetWidth(img); bpp=FreeImage_GetBPP(img); re=FreeImage_Allocate(w,h,bpp); } void Calc(int ymin,int ymax) { for (int y=ymin;y) { for (int x=0;x ) { RGBQUAD color; FreeImage_GetPixelColor(img,x,y,&color); color.rgbBlue-=255; color.rgbGreen-=255; color.rgbRed-=255; FreeImage_SetPixelColor(re,x,y,&color); } } } void CalcAll() { Calc(0,h); } //每个线程处理图像的1/4 void Calc1(PVOID param) { Calc(0,int(h/4)); } void Calc2(PVOID param) { Calc(int(h/4),int(h/2)); } void Calc3(PVOID param) { Calc(int(h/2),int(3*h/4)); } void Cal(PVOID param) { Calc(int(3*h/4),h); } void main() { double start,end; HANDLE hThread[4]; Init(); start=clock(); CalcAll(); end=clock(); cout< endl; start=clock(); hThread[0]=(HANDLE)_beginthread(Calc1,0,NULL); hThread[1]=(HANDLE)_beginthread(Calc2,0,NULL); hThread[2]=(HANDLE)_beginthread(Calc3,0,NULL); hThread[3]=(HANDLE)_beginthread(Cal,0,NULL); WaitForMultipleObjects(4,hThread,true,INFINITE); end=clock(); cout< endl; FreeImage_Unload(img); FreeImage_Unload(re); system("pause"); }
后记:
我再次对其进行了测试,计算机可以使用openmp加速,您需要打开vs2010 openmp优化选项,然后将Calc()函数更改为以下形式:
void Calc(int ymin,int ymax) { RGBQUAD color; #pragma omp parallel for schedule(dynamic, 1) private(color) for (int y=ymin;y) { for (int x=0;x ) { FreeImage_GetPixelColor(img,x,y,&color); color.rgbBlue-=255; color.rgbGreen-=255; color.rgbRed-=255; FreeImage_SetPixelColor(re1,x,y,&color); } } }

速度比我自己编写的多线程要快。
后记:
最后,我仍然建议使用我自己编写的多线程。不建议使用OpenMP,因为使用openMP处理后图像会产生很多凹痕,这是不可接受的,就像下面这样:

使用自控多线程时没有这种问题。
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/shoujiruanjian/article-358037-1.html
哎呀杨洋啊
允许有言论自由