gpt4 book ai didi

c++ - 为什么 C++ std::string.length() 在 VS2017 上比 strlen() 慢?

转载 作者:搜寻专家 更新时间:2023-10-31 02:04:35 26 4
gpt4 key购买 nike

我已经在 VS2017 上测试了 c++ std::string.length()strlen() 函数,如下所示。结果是:

msvs 2017

令我惊讶的是 string.length()strnlen()7x。但我想 string.length() 是一个 O(1) 操作,而 strlen() 是一个 O(n) 操作。

我还在 coding ground 上的 GNU GCC v7.1.1 上对其进行了测试

它显示 string.length()strlen() 稍微快(没有我预期的那么快。)

enter image description here

这是为什么?我的测试代码有问题吗?

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;
}

最佳答案

回答我自己的问题:

根据@Ken Y-N 和@PaulMcKenzie 的建议,我将 stopwatch 的范围本地化了排除 cout 的时间,并用 Release 构建它 build 。结果现在对我来说很有意义!

enter image description here

关于c++ - 为什么 C++ std::string.length() 在 VS2017 上比 strlen() 慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53291954/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com