字符串格式化
参照下面的文章
http://www.cnblogs.com/james6176/p/3222671.html
http://blog.csdn.net/yunhua_lee/article/details/6381876
结果修改代码windows+vs2010代码如下
#include <iostream>
#include <string>
#include <time.h>
#include <sstream>
#include <stdio.h>
#include <vector>
using namespace std;
#define OUT_IN_REPEATE_NUM 10000
#define IN_REPEATE_NUM 60
string s1="abcedfg";
string s2="hijklmn";
string s3="opqrst";
void plusTest(string& ret)
{
for(int i=0; i<IN_REPEATE_NUM; i++)
{
ret += s1;
ret += s2;
ret += s3;
}
}
void appendTest(string& ret)
{
for(int i=0; i<IN_REPEATE_NUM; i++)
{
ret.append(s1);
ret.append(s2);
ret.append(s3);
}
}
void sprintfTest(string& ret)
{
const size_t length=26*IN_REPEATE_NUM;
char tmp[length];
char* cp = tmp;
size_t strLength=s1.length()+s2.length()+s3.length();
for(int i=0; i<IN_REPEATE_NUM; i++)
{
sprintf(cp,"%s%s%s", s1.c_str(), s2.c_str(),s3.c_str());
cp+=strLength;
}
ret = tmp;
}
void ssTest(string& ret)
{
stringstream ss;
for(int i=0; i<IN_REPEATE_NUM; i++)
{
ss<<s1;
ss<<s2;
ss<<s3;
}
ret = ss.str();
}
string ss, plus, append, sprintf;
clock_t sTime, eTime;
sTime = clock();
for(int i=0; i<OUT_IN_REPEATE_NUM; i++)
{
sprintf="";
sprintfTest(sprintf);
}
eTime = clock();
long SprintfTime = eTime-sTime;
sTime = clock();
for(int i=0; i<OUT_IN_REPEATE_NUM; i++)
{
append="";
appendTest(append);
}
eTime = clock();
long AppendTime = eTime-sTime;
sTime = clock();
for(int i=0; i<OUT_IN_REPEATE_NUM; i++)
{
ss="";
ssTest(ss);
}
eTime = clock();
long SsTime = eTime-sTime;
sTime = clock();
for(int i=0; i<OUT_IN_REPEATE_NUM; i++)
{
plus="";
plusTest(plus);
}
eTime = clock();
long PlusTime = eTime-sTime;
cout<<"PlusTime is : "<<PlusTime<<endl;
cout<<"AppendTime is : "<<AppendTime<<endl;
cout<<"SsTime is : "<<SsTime<<endl;
cout<<"SprintfTime is :"<<SprintfTime<<endl;
if(ss==sprintf && append==plus && ss==plus)
{
cout<<"They are same"<<endl;
}
else
{
cout<<"Different!"<<endl;
cout<<"Sprintf: "<<sprintf<<endl;
cout<<"ss: "<<ss<<endl;
cout<<"Plus: "<<plus<<endl;
cout<<"Append:"<<append<<endl;
}
system("pause");
测试发现不同的结果
debug下测试结果
PlusTme is : 610
AppendTime is:570
SsTim is :798
SprintfTime is:327
写文章前差点认为这就是最终结果,从而误导自己
release下测试结果
PlusTime is:15
AppendTime is:15
SsTime is:142
SprintfTime is :110
相差很多
结合以上得出结论std::string使用+=性能最好