高级C++和Cuda学习笔记

(1)我要定义一个计时函数,即需要对任何一个动作计时,设计的代码如下:

#include <iostream>
#include <string>
#include <chrono>
#include <format>
#include <thread>

using namespace std;

template <typename Func>
void timeIt(string name, Func func) {
    auto start = chrono::system_clock::now();
    cout << format("{:%Y-%m-%d %H:%M:%S}", start) << ": " << name << " start" << endl;
    func();
    auto end = chrono::system_clock::now();
    auto ms = chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
    cout << format("{:%Y-%m-%d %H:%M:%S}", end) << ": " << name << " end, time cost " << ms << " ms" << endl;
}

int main() {
    string str = "Hello";
    timeIt("test", [&str]() {     
        cout << str << endl;
        str += " World!";
        //do nothing
    });
    cout << str << endl;
    
    return 0;
}

要求C++ 20以上(format需要20)。C++ 11以上方支持lambda表达式。

C++ lambda表达式的捕获、Mutable特性挺有意思,需要进一步研究。

0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注