Skip to main content
  1. Posts/

C++ 记录代码运行时间

·169 words·1 min
Note: This article is available in Chinese only. 本文暂无英文版本。 View original

以前用的办法太老土啦

看到一个since C++11的方法,我觉得比较优雅

 1    #include <iostream>
 2    #include <chrono>
 3    //#include <ratio>
 4    #include <thread>
 5
 6    void f()
 7    {
 8        std::this_thread::sleep_for(std::chrono::seconds(1));
 9    }
10
11    int main()
12    {
13        auto t1 = std::chrono::high_resolution_clock::now();
14        f();
15        auto t2 = std::chrono::high_resolution_clock::now();
16
17        // floating-point duration: no duration_cast needed
18        std::chrono::duration<double, std::milli> fp_ms = t2 - t1;
19
20        // integral duration: requires duration_cast
21        auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
22
23        // converting integral duration to integral duration of shorter divisible time unit:
24        // no duration_cast needed
25        std::chrono::duration<long, std::micro> int_usec = int_ms;
26
27        std::cout << "f() took " << fp_ms.count() << " ms, "
28                  << "or " << int_ms.count() << " whole milliseconds "
29                  << "(which is " << int_usec.count() << " whole microseconds)" << std::endl;
30    }

Related

gdb学习笔记

·235 words·1 min
用gdb调试c++的时候,需要添加-g编译选项add_compile_options(-g),并且关掉各种编译优化

Eigen: C++开源矩阵学习笔记

·736 words·2 mins
接触 Eigen 的原因是最近在看 caffe/caffe2 源码,caffe2 中使用了 Eigen 库。Eigen 是一个基于 C++ 模板的线性代数库,直接将库下载后放在项目目录下,然后包含头文件就能使用,非常方便。对于 Linux 用户,只需要把头文件放到 /usr/include 下即可。此外,Eigen 的接口清晰,稳定高效。