您的位置:首页 > 编程语言 > C语言/C++

C++的string逐位处理效率比较

2012-09-20 16:41 134 查看
 

今天看到一个对string做逐位处理的代码,我看见代码使用指针来指向string,我就在想为什么不用中括号,型如string s; s[i] = ....; 这种操作。

 

想到这个代码作者一向以效率优先考虑,于是我测试了一下效率,果不其然。。。哈哈

 

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
using namespace std;

static unsigned long GetTimeMicros()
{
struct timeval tv;
long time;
gettimeofday(&tv, NULL);
time = tv.tv_sec;
return (((unsigned long)tv.tv_sec) * 1000000) + tv.tv_usec;
}

string forceLower(string astr)
{
char* str = const_cast<char*>(astr.c_str());
for (size_t i = 0; i <= astr.size(); ++i)
{
if (str[i] >= 'A' && str[i] <= 'Z')
{
str[i] += 32;
}
}
return astr;
}

string forceLower2(string astr)
{
for (size_t i = 0; i < astr.size(); ++i)
{
if (astr[i] >= 'A' && astr[i] <= 'Z')
{
astr[i] += 32;
}
}
return astr;
}

int main()
{
string s = "ASFOAiLJSLDJFLSDLKFKJSDLWJERA";

int start, end;

start = GetTimeMicros();
for (int i = 0; i < 100000; i++)
{
forceLower(s);
}
end = GetTimeMicros();
cout << "做10万次转小写操作(用指针),耗时(微秒): " << end - start << endl;

start = GetTimeMicros();
for (int i = 0; i < 100000; i++)
{
forceLower2(s);
}
end = GetTimeMicros();
cout << "做10万次转小写操作(用中括号),耗时(微秒): " << end - start << endl;

return 0;
}


 

输出:

做10万次转小写操作(用指针),耗时(微秒): 31013

做10万次转小写操作(用中括号),耗时(微秒): 81645

可以看出来,有效率是三倍的差距。在做高性能的程序,只有每个细节都全力保证高性能,才能为实现整体高性能添砖加瓦!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string c++ struct null 测试