我已经在 VS2017 上测试了c ++ std::string.length()
与strlen()
函数,如下所示。结果是:
令我惊讶的是,string.length()
比strnlen()
慢7倍。但是我想string.length()
是O(1)
操作,而strlen()
是O(n)
操作。
我还在coding ground的GNU GCC v7.1.1上进行了测试
它显示string.length()
比strlen()
快(不如我预期的那样)。
为什么?我的测试代码有问题吗?
class stopwatch
{
public:
stopwatch()
{
start = std::chrono::system_clock::now();
}
~stopwatch()
{
auto end = std::chrono::system_clock::now();
auto elasped = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
cout << "elasped: " << elasped.count() << endl;
}
private:
chrono::system_clock::time_point start;
};
void test_std_str(const string& ss)
{
stopwatch sw;
const int max = 100000;
int sum = 0;
for (int i = 0; i < max; i++)
{
sum += ss.length();
}
cout<< "test_string: sum = " << sum << endl;
}
void test_c_str(const char* str)
{
stopwatch sw;
const int max = 100000;
int sum = 0;
for (int i = 0; i < max; i++)
{
sum += strlen(str);
}
cout << "test_c_str: sum = " << sum << endl;
}
int main()
{
std::string ss = "abcdef";
const char* str = "abcdef";
int x;
cin >> x;
if (x > 0)
{
ss = "helloworld";
str = "helloworld";
}
test_std_str(ss);
test_c_str(str);
return 0;
}