c++ - 如何测试特定的 C++ 语句是否比其他语句快或慢?

标签 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'

这只是一个近似值,因为其他机器的性能可能不同...

至于为什么会这样:

  1. 单个字符(1 字节)常量比具有单个字符的字符串小得多(以字节为单位),因为字符串是 pointer到 char(指向内存中的指定地址),它比内存中的单个 char 占用更多空间,因为它是一个容器(for memory addresses of每个字符)毕竟...( const char*)...
  2. 字符和字符串的读取方式有所不同...在迭代字符串时直接访问字符并对每个字符指向执行操作并存储结果回到指针的地址里面...
  3. 字符串始终是一个 char 数组,而 char 被安全地视为一个包含相应 numerical value 的整数(Extended ASCII,不同的字符编码从中分出)它,1个字符的字符串是1个字符的数组(连同它的地址.. .), 事实上,它不等于单个字符...

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/

相关文章:

java - 为什么 JIT 会在启动时编译一些方法?

松紧带快速松弛算法

css - 我需要你对 CSS 优化的意见

mysql - 将 ORDER BY 'x' 与 JOIN 一起使用,但保留没有 'x' 值的行

c++ - OpenCV 双矩阵除以标量产生不正确的结果

c++ - 在windows下为linux编译C++代码,as ready to run

c++ - 在 A 或 B 的任何容器上重载模板成员函数

c++ - For 遍历模板参数/类型

Mysql查询优化-范围搜索

c++ - 子集相关的位操作