time_t
在Linux中的类型其实是long int
1 | struct timeval tv; |
高精度计时
c++11的高精度计时方法,要先配置C++11环境:1
2
3
4
5
6
7
8
9
10
11
using namespace chrono;
auto start = system_clock::now();
/* do something */
auto end = system_clock::now();
auto duration = duration_cast<microseconds>(end - start);
cout << "花费了"
<< double(duration.count()) * microseconds::period::num / microseconds::period::den
<< "秒" << endl;
有时候可能报错:error: ‘chrono’ in namespace ‘std’ does not name a type
解决方法: 改为using namespace std::chrono;
in addition to #include <chrono>
或者用steady_clock
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using std::chrono::steady_clock;
// 这个类型是 steady_clock::time_point
auto t1 = std::chrono::steady_clock::now();
// your code
auto t2 = std::chrono::steady_clock::now();
//秒
double dr_s=std::chrono::duration<double>(t2-t1).count();
//毫秒
double dr_ms=std::chrono::duration<double,std::milli>(t2-t1).count();
//微秒
double dr_us=std::chrono::duration<double,std::micro>(t2-t1).count();
//纳秒
double dr_us=std::chrono::duration<double,std::nano>(t2-t1).count();
ALOAM中的TicToc
类其实就是std::chrono::steady_clock::now()
拥有从毫秒到小时的计时1
2
3
4std::chrono::milliseconds
std::chrono::seconds
std::chrono::minutes
std::chrono::hours
可以用于休眠函数1
2std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::this_thread::sleep_for(std::chrono::seconds(1));