- 编写的代码经常需要观察运行的效率,需要使用一些常规的时间统计的方法去进行测量具体是那一部分的代码耗时严重,但由于cpp 获取系统时间的方法不太精确,可以使用下面两种方法进行测量
使用std::chrono 库
#include <iostream>
#include <ratio>
#include <chrono>
int main (){
using namespace std::chrono;
high_resolution_clock::time_point t1 = high_resolution_clock::now();
std::cout << "printing out 1000 stars...\n";
for (int i=0; i<1000; ++i)
{
std::cout << "*";
std::cout << std::endl;
}
high_resolution_clock::time_point t2 = high_resolution_clock::now();
duration<double, std::milli> time_span = t2 - t1;
std::cout << "It took me " << time_span.count() << " milliseconds.";
std::cout << std::endl;
return 0;
}
// SI TYPEDEFS
typedef ratio<1, 1000000000000000000LL> atto;
typedef ratio<1, 1000000000000000LL> femto;
typedef ratio<1, 1000000000000LL> pico;
typedef ratio<1, 1000000000> nano;
typedef ratio<1, 1000000> micro;
typedef ratio<1, 1000> milli;
typedef ratio<1, 100> centi;
typedef ratio<1, 10> deci;
typedef ratio<10, 1> deca;
typedef ratio<100, 1> hecto;
typedef ratio<1000, 1> kilo;
typedef ratio<1000000, 1> mega;
typedef ratio<1000000000, 1> giga;
typedef ratio<1000000000000LL, 1> tera;
typedef ratio<1000000000000000LL, 1> peta;
typedef ratio<1000000000000000000LL, 1> exa;
2.获取cpu 时间,这种方法可以测量出ns 级别的时间耗时,用cpu cycle / cpu 主频 就能得到时间
__u64 rdtsc()
{
__u32 lo,hi;
__asm__ __volatile__
(
"rdtsc":"=a"(lo),"=d"(hi)
);
return (__u64)hi<<32|lo;
}