<分区>
例如,当打印单个字符(如换行符)时,在 C++ 中使用 cout
时,作为字符串或字符传递可能会更快?
cout << "\n";
或者
cout << '\n';
This video激励我编写高效的代码。
您将如何着手测试这些东西?也许我可能想测试其他东西,看看哪个更快,所以了解如何自己测试这些东西会很有帮助。
标签 c++ optimization
<分区>
例如,当打印单个字符(如换行符)时,在 C++ 中使用 cout
时,作为字符串或字符传递可能会更快?
cout << "\n";
或者
cout << '\n';
This video激励我编写高效的代码。
您将如何着手测试这些东西?也许我可能想测试其他东西,看看哪个更快,所以了解如何自己测试这些东西会很有帮助。
最佳答案
理论上,是,使用'\n'
而不是”\n"
除去打印1000 次相同good-ol 换行的耗用时间后速度相当快:
Remember: A single char possibly cannot be slower than a pointer... since a pointer points to addresses of each char (like a container) and this is why its byte size is not fixed, and a char only has one address and that is itself... of only 1 byte
// Works with C++17 and above...
#include <iostream>
#include <chrono>
template<typename T, typename Duration = std::chrono::milliseconds, typename ...Args>
constexpr static auto TimeElapsedOnOperation(T&& functor, Args&&... arguments)
{
auto const ms = std::chrono::steady_clock::now();
std::invoke(std::forward<decltype(functor)>(functor),
std::forward<Args>(arguments)...);
return std::chrono::duration_cast<std::chrono::
milliseconds>(std::chrono::steady_clock::now() - ms);
}
int main()
{
std::cout << TimeElapsedOnOperation([]
{
for (auto i = 0; i < 1000; i++)
std::cout << "\n";
}).count() << std::endl;
std::cin.get();
std::cout << TimeElapsedOnOperation([]
{
for (auto i = 0; i < 1000; i++)
std::cout << '\n';
}).count() << std::endl;
std::cin.get();
return 0;
}
它给出了以下输出:(可能发生不同...)
<1000> newlines follow...
2195 milliseconds For the string
"\n"
More <1000> newlines follow...
852 milliseconds For the character
'\n'
2195 - 852 = 1343 毫秒
它花费了 1343(1.343 秒)毫秒...所以我们可以近似地认为它是 61.18%(1343/2195 * 100) 比仅使用 '\n'
这只是一个近似值,因为其他机器的性能可能不同...
至于为什么会这样:
const char*
)...So maybe (just maybe) you are on the better side of using
'\n'
instead...
但是,一些“棘手”编译器可能会将您的代码从"\n"
优化为'\n'
任何时候......,所以,实际上,我们永远无法猜测,但是,将 char
声明为 仍然是被认为是好的做法字符
...
关于c++ - 如何测试特定的 C++ 语句是否比其他语句快或慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53236268/