1.#include <time.h>
特点:本质上计算cpu的tick()数,然后通过除以CLOCKS_PER_SEC获得秒数,当线程sleep时,不计算时间,即计算的不是程序真实的运行耗时。
应用方法:使用time.h计算程序运行时间
#include <time.h>
#include <unistd>//包含sleep函数
#include <iostream>
using namespace std;
int main()
{
clock_t startTime,endTime;
startTime=clock();
sleep(1);
endTime=clock();
std::cout<<"consume time="<<(endTime-startTime)/CLOCKS_PER_SEC<<std::endl;
return 0;
}
2.#include
特点:chrono库中包含system_clock、steady_clock和high_resolution_clock三种时钟,此处只介绍high_resolution_clock。可用来计算相对时间,并方便地转化为s、ms、min、hour,计算代码运行的真实时间,包含休眠时间。
函数①.now()函数。可以返回从公元0年(或许)到现在的时间间隔,返回类型为time_point;
函数②duration.count()函数。time_point和duration为两种时间存储方式,可通过time_point–>duration–>.count()获取double类型的时间间隔;
函数③std::this_thread::sleep_until(sleep_time)。表示休眠到指定时间,接受high_resolution_clock::time_point数据类型
详细介绍见:https://blog.youkuaiyun.com/cw_hello1/article/details/66476290
#include <iostream>
#include <thread>
#include <chrono>//包含头文件
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
void callback_1(){
while(1){
clock_t start_time=clock();
// 获取当前时间点
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
// 设置休眠时间为当前时间点加上100ms
std::chrono::high_resolution_clock::time_point sleep_time = now + std::chrono::milliseconds(100);
// 休眠直到指定的时间点
std::this_thread::sleep_until(sleep_time);
// 输出休眠结束后的时间点
std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::ratio<1,1>> duration_s(end-start);//转换为s
// std::chrono::duration<double,std::ratio<1,1000>> duration_ms(end-start);//转换为ms,1/1000s为单位
std::cout << "thread1 Finished sleeping at " << duration_s.count() <<"second"<< std::endl;
// std::cout << "thread1 Finished sleeping at " << duration_ms.count() <<"millisecond"<< std::endl;
}
}
void callback_2(){
while(1){
clock_t start_time=clock();
// 获取当前时间点
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
// 设置休眠时间为当前时间点加上200ms
std::chrono::high_resolution_clock::time_point sleep_time = now + std::chrono::milliseconds(200);
// 休眠直到指定的时间点
std::this_thread::sleep_until(sleep_time);
// 输出休眠结束后的时间点
std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::ratio<1,1>> duration_s(end-start);
std::cout << "thread2 Finished sleeping at " << duration_s.count() << std::endl;
}
}
int main() {
std::thread th1(callback_1),th2(callback_2);
th1.join();
th2.join();
return 0;
}