C風(fēng)格字符串與標(biāo)準(zhǔn)庫string類型性能對比
Posted on 2006-05-01 23:58 Tauruser 閱讀(6392) 評論(20) 編輯 收藏 引用 所屬分類: 算法與數(shù)據(jù)結(jié)構(gòu) 今天在看c++ primer書中挺到C風(fēng)格字符串與標(biāo)準(zhǔn)庫string類型的效率問題。推薦使用string類型,不但因?yàn)槠涓踩乙蚱湫矢摺W詈笥刑岬揭粋€(gè)數(shù)據(jù)。
“平均來說,使用string類型的程序執(zhí)行速度要比用C風(fēng)格字符串的快很多,在我們用了五年的PC機(jī)上其平均執(zhí)行速度分別是:
user?? 0.47??? #string class
??????? user?? 2.55??? #C-style haracter string”
對這個(gè)數(shù)據(jù)表示相當(dāng)?shù)捏@訝。于是自已寫了個(gè)程序,測試一下兩個(gè)類型的效率。
#include?<iostream>
#include?<string>
#include?<ctime>
using?namespace?std;
const?size_t?retime=1000000;
int?main()


{
????clock_t?start,?finish;
????start=clock();
????const?char?*pc="a?very?long?literal?string";
????const?size_t?len?=?strlen(pc);
????for(size_t?ix=0;?ix!=retime;++ix)

????
{
????????char?*pc2=?new?char[len+1];
????????strcpy(pc2,pc);
????????if(strcmp(pc2,pc))
??????????;
????????delete?[]pc2;
????}
????finish=clock();
????cout<<"C-style?string?run?"<<retime<<"?times?needs?"<<finish-start<<"?clock?times";
????cout<<endl;

????start=clock();
????string?str("a?very?long?literal?string");
????for(size_t?ix=0;ix!=retime;++ix)

????
{
????????string?str2=str;
????????if(str!=str2)
??????????;
????}
????finish=clock();
????cout<<"C++?string?run?"<<retime<<"?times?needs?"<<finish-start<<"?clocks";
????cout<<endl;
????return?0;

}
上述程序在CentOS下編譯并運(yùn)行測試得數(shù)據(jù)平均在:
C-style string run 1000000 times needs?240000 clock times
C++ string run 1000000 times needs 110000clocks
在這個(gè)數(shù)據(jù)下明顯string的效率要高。
而在windows下使用vc6.0 release編譯并運(yùn)行,數(shù)據(jù)平均在:
C-style string run 1000000 times needs?350 clock times
C++ string run 1000000 times needs?350 clocks
兩種類型的效率差不多
繼續(xù)在vs2005下release編譯,數(shù)據(jù)平均在:
C-style string run 1000000 times needs?320 clock times
C++ string run 1000000 times needs 370 clocks
string效率要低一個(gè)。
在Linux平臺下,string的效率比C-style的要整整高出一倍有多。
而在windows平臺下,sting不但效率上的優(yōu)勢沒有了,反而比C-style還要差。
不知道這是什么原因。為什么在unix下要比在windows下快如此的多。而在windows上卻不行?
快的原因在哪呢?
PS:
不知道我的測試程序這樣子寫是否可以。
“平均來說,使用string類型的程序執(zhí)行速度要比用C風(fēng)格字符串的快很多,在我們用了五年的PC機(jī)上其平均執(zhí)行速度分別是:
user?? 0.47??? #string class
??????? user?? 2.55??? #C-style haracter string”
對這個(gè)數(shù)據(jù)表示相當(dāng)?shù)捏@訝。于是自已寫了個(gè)程序,測試一下兩個(gè)類型的效率。












































C-style string run 1000000 times needs?240000 clock times
C++ string run 1000000 times needs 110000clocks
在這個(gè)數(shù)據(jù)下明顯string的效率要高。
而在windows下使用vc6.0 release編譯并運(yùn)行,數(shù)據(jù)平均在:
C-style string run 1000000 times needs?350 clock times
C++ string run 1000000 times needs?350 clocks
兩種類型的效率差不多
繼續(xù)在vs2005下release編譯,數(shù)據(jù)平均在:
C-style string run 1000000 times needs?320 clock times
C++ string run 1000000 times needs 370 clocks
string效率要低一個(gè)。
在Linux平臺下,string的效率比C-style的要整整高出一倍有多。
而在windows平臺下,sting不但效率上的優(yōu)勢沒有了,反而比C-style還要差。
不知道這是什么原因。為什么在unix下要比在windows下快如此的多。而在windows上卻不行?
快的原因在哪呢?
PS:
不知道我的測試程序這樣子寫是否可以。