托管代码和非托管代码效率的对比

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

托管代码和非托管代码效率的对比。2006-12-0710:14by无常,12026visits,收藏,编辑一直以来只知道托管代码的效率要比非托管代码低,至于低多少也没有可参考的数据。今天在csdn看到的英特尔多核平台编程优化大赛的广告,把里面的代码下载回来,分别用非托管c/托管cpp/c#做了个简略的性能测试,不比不知道,一比吓了一跳。且看数据说话。第一步:原始代码如:/*computethepotentialenergyofacollectionof*//*particlesinteractingviapairwisepotential*/#includestdio.h#includestdlib.h#includemath.h#includewindows.h#includetime.h#defineNPARTS1000#defineNITER201#defineDIMS3intrand(void);intcomputePot(void);voidinitPositions(void);voidupdatePositions(void);doubler[DIMS][NPARTS];doublepot;doubledistx,disty,distz,dist;intmain(){inti;clock_tstart,stop;initPositions();updatePositions();start=clock();for(i=0;iNITER;i++){pot=0.0;computePot();if(i%10==0)printf(%5d:Potential:%10.3f\n,i,pot);updatePositions();}stop=clock();printf(Seconds=%10.9f\n,(double)(stop-start)/CLOCKS_PER_SEC);inte;scanf(%d,&e);}voidinitPositions(){inti,j;for(i=0;iDIMS;i++)for(j=0;jNPARTS;j++)r[i][j]=0.5+((double)rand()/(double)RAND_MAX);}voidupdatePositions(){inti,j;for(i=0;iDIMS;i++)for(j=0;jNPARTS;j++)r[i][j]-=0.5+((double)rand()/(double)RAND_MAX);}intcomputePot(){inti,j;for(i=0;iNPARTS;i++){for(j=0;ji-1;j++){distx=pow((r[0][j]-r[0][i]),2);disty=pow((r[1][j]-r[1][i]),2);distz=pow((r[2][j]-r[2][i]),2);dist=sqrt(distx+disty+distz);pot+=1.0/dist;}}return0;}执行结果如下:执行时间4.609s。第二步:托管新建一个C++CLRConsoleAplication,命名为mcpp。打开mcpp.cpp文件,将原始代码粘贴进来即可(代码太长这里就不贴出来了,可以在全贴下面的下载全部源码)。执行结果如下:执行时间:15.1720s。第二步:c#笔者将原始代码翻译成CS代码,如下:usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespacecs{classProgram{privateconstintRAND_MAX=0x7fff;privateconstintNPARTS=1000;privateconstintNITER=201;privateconstintDIMS=3;privatedoublepot;privatedoubledistx,disty,distz,dist;privateRandomrandom=newRandom(Environment.TickCount);privatedouble[][]r=newdouble[DIMS][];publicvoidmain(){inti;intstart,stop;for(intii=0;iiDIMS;ii++){r[ii]=newdouble[NPARTS];}initPositions();updatePositions();start=Environment.TickCount;for(i=0;iNITER;i++){pot=0.0;computePot();if(i%10==0)Console.WriteLine({0}:Potential:{1:##########.###},i,pot);updatePositions();}stop=Environment.TickCount;Console.WriteLine(Seconds={0:##########.#########},(double)(stop-start)/1000);}privatevoidcomputePot(){inti,j;for(i=0;iNPARTS;i++){for(j=0;ji-1;j++){distx=Math.Pow((r[0][j]-r[0][i]),2);disty=Math.Pow((r[1][j]-r[1][i]),2);distz=Math.Pow((r[2][j]-r[2][i]),2);dist=Math.Sqrt(distx+disty+distz);pot+=1.0/dist;}}}privatevoidupdatePositions(){inti,j;for(i=0;iDIMS;i++)for(j=0;jNPARTS;j++)r[i][j]-=0.5+((double)random.Next(RAND_MAX)/(double)RAND_MAX);}privatevoidinitPositions(){inti,j;for(i=0;iDIMS;i++)for(j=0;jNPARTS;j++)r[i][j]=0.5+((double)random.Next(RAND_MAX)/(double)RAND_MAX);}staticvoidMain(string[]args){Programp=newProgram();p.main();Console.ReadLine();}}}执行结果如下:执行时间:62.453s!第四、数据比较非托管C:4.609s托管cpp:15.720s托管c#:62.453sPS机器配置:p43.0G双核,1G内存

1 / 7
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功