资源描述:
《如何编写高效简洁的c语言(how to write efficient and concise c language)》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、如何编写高效简洁的c语言(HowtowriteefficientandconciseClanguage)Introduction:ThegoalofmanysoftwareengineersistowriteefficientandconciseClanguagecode.Inthispaper,theworkofsomeexperienceandexperiencetodorelatedelaboration,nottheplace,pleaseadvise.Thefirsttrick:takespacefortimeThebiggestcontradi
2、ctioninacomputerprogramisacontradiction,spaceandtimethen,startingfromtheangleofreversethinkingtoconsidertheefficiencyoftheprogram,wehavetosolvetheproblemofthefirststrokes--aspacefortime.Forexample,theassignmentofstrings.MethodA,theusualway:#defineLEN32Charstring1[LEN];Memset(strin
3、g1,0,LEN);Strcpy(string1,"Thisisaexample!!");MethodB:Constcharstring2[LEN]="Thisisaexample"!";Char*cp;CP=string2;Itcanbeoperateddirectlywithpointerwhenusing.)Fromtheaboveexample,wecanseethattheefficiencyofAandBisnotcomparable.Inthesamestoragespace,Bcanoperatedirectlywithpointers,a
4、ndAneedstocalltwocharacterfunctionstocomplete.TheweaknessofBisflexibility,notA.Whenyouneedtochangeastringcontentfrequently,Ahasbetterflexibility;ifusingtheBmethod,youneedtodepositmanystrings,althoughoccupyalargeamountofmemory,buttheprogramexecutionefficiency.Ifthesystemhashighreal
5、-timerequirementsandmemory,thenIrecommendyouusethistrick.Thetrickofthistrickistousemacrosinsteadoffunctions.Examplesareasfollows:MethodC:#definebwMCDR2_ADDRESS4#definebsMCDR2_ADDRESS17IntBIT_MASK(int__bf){Return((1U(BW##__bf))-1(BS),__bf##);}VoidSET_BITS(int__dst,int__bf,int__val)
6、{__dst=((__dst)&(BIT_MASK~(__bf))
7、)(((__val)(BS<##&(__bf))BIT_MASK(__bf))))}SET_BITS(MCDR2,MCDR2_ADDRESS,RegisterNumber);MethodD:#definebwMCDR2_ADDRESS4#definebsMCDR2_ADDRESS17#definebmMCDR2_ADDRESSBIT_MASK(MCDR2_ADDRESS)#defineBIT_MASK(__bf)((("1U(BW__bf##))-1(BS),__bf##))#define
8、SET_BITS(__dst,__bf,__val)((__dst)=((__dst)&(BIT_MASK~(__bf))
9、)(((__val)(BS<##&(__bf))BIT_MASK(__bf))))SET_BITS(MCDR2,MCDR2_ADDRESS,RegisterNumber);Thedifferencebetweenfunctionandmacrofunctionisthatthemacrofunctiontakesupalotofspace,andthefunctiontakesuptime.Youneedtoknowisthatthe
10、functioncallistousethesystemstack