参考【C++】计算时间差 - CrazyTomato - 博客园
1.clock()
标准库中ctime头文件
#include <ctime>
#include <iostream>
using namespace std;
int main(){
clock_t start = clock(); //获取当前系统时间
function();
clock_t end = clock();
double programTimes = ((double) end -start) / CLOCKS_PER_SEC;
}
2.high_resolution_clock
chrono (C++11新增程序库)
#include <chrono>
#include <thread>
#include <iostream>
using namespace std;
int main(){
auto beginTime = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(20));
auto endTime = std::chrono::high_resolution_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::microseconds>(endTime-beginTime);
double programTimes = ((double) elapsedTime.count(); //programTimes:20000
}
- seconds (): 返回秒计的unix时间戳
- milliseconds (): 返回毫秒计的unix时间戳
- microseconds (): 返回微秒计的unix时间戳