今天在看c++ primer書中挺到C風格字符串與標準庫string類型的效率問題。推薦使用string類型,不但因為其更安全,且因其效率更高。最后有提到一個數據。
“平均來說,使用string類型的程序執行速度要比用C風格字符串的快很多,在我們用了五年的PC機上其平均執行速度分別是:
user?? 0.47??? #string class
??????? user?? 2.55??? #C-style haracter string”
對這個數據表示相當的驚訝。于是自已寫了個程序,測試一下兩個類型的效率。
#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下編譯并運行測試得數據平均在:
C-style string run 1000000 times needs?240000 clock times
C++ string run 1000000 times needs 110000clocks
在這個數據下明顯string的效率要高。
而在windows下使用vc6.0 release編譯并運行,數據平均在:
C-style string run 1000000 times needs?350 clock times
C++ string run 1000000 times needs?350 clocks
兩種類型的效率差不多
繼續在vs2005下release編譯,數據平均在:
C-style string run 1000000 times needs?320 clock times
C++ string run 1000000 times needs 370 clocks
string效率要低一個。
在Linux平臺下,string的效率比C-style的要整整高出一倍有多。
而在windows平臺下,sting不但效率上的優勢沒有了,反而比C-style還要差。
不知道這是什么原因。為什么在unix下要比在windows下快如此的多。而在windows上卻不行?
快的原因在哪呢?
PS:
不知道我的測試程序這樣子寫是否可以。
“平均來說,使用string類型的程序執行速度要比用C風格字符串的快很多,在我們用了五年的PC機上其平均執行速度分別是:
user?? 0.47??? #string class
??????? user?? 2.55??? #C-style haracter string”
對這個數據表示相當的驚訝。于是自已寫了個程序,測試一下兩個類型的效率。












































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