sleep() 和 usleep()主要区别前者单位为秒,后者为微妙(*1e6)
C++ sleep() 和 usleep()
代码如下:设置一个时间参数,分别向sleep()和usleep()方法传入该参数,打印sleep和usleep前后的系统时间戳
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <unistd.h>
using namespace std;
int main(int argc, char *argv[]){
int sleep_time = 100;
cout << "sleep before time: " << time(NULL) << endl;
sleep(sleep_time);
cout << "sleep after time: " << time(NULL) << endl;
cout << "======================" << endl;
cout << "usleep before time: " << time(NULL) << endl;
usleep(sleep_time);
cout << "usleep after time: " << time(NULL) << endl;
}
运行结果:
sleep before time: 1560257692
sleep after time: 1560257792
======================
usleep before time: 1560257792
usleep after time: 1560257792
从运行结果来看,sleep()方法执行前后的时间戳相减正好是sleep_time大小,打印的时间戳是以秒为单位的,所以sleep()方法将程序挂起使用的单位是秒级别的;从usleep()执行前后的时间戳来看,感觉上程序并没有被挂起,这是因为usleep()方法将程序挂起的使用的单位是微秒级别的(1,000,000 微秒 = 1秒)所以程序看起来并没有被挂起,下面我们将打印的时间戳改为微秒级别的看看。
可以通过<sys/time.h>库中的gettimeofday()方法来拿到当前系统的微秒级别时间。
#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <sys/time.h>
using namespace std;
int main(int argc, char *argv[]){
int sleep_time = 100;
cout << "sleep before time: " << time(NULL) << endl;
sleep(sleep_time);
cout << "sleep after time: " << time(NULL) << endl;
cout << "======================" << endl;
cout << "usleep before time: " << time(NULL) << endl;
usleep(sleep_time);
cout << "usleep after time: " << time(NULL) << endl;
cout << "======================" << endl;
struct timeval tv;
gettimeofday(&tv,NULL);
cout << "not usleep before time: " << tv.tv_sec<<"s,"<<tv.tv_usec<<"微秒"<<endl;
usleep(0);
gettimeofday(&tv,NULL);
cout << "not usleep after time: " << tv.tv_sec<<"s,"<<tv.tv_usec<<"微秒"<<endl;
cout << "======================" << endl;
gettimeofday(&tv,NULL);
cout << "usleep before time: " << tv.tv_sec<<"s,"<<tv.tv_usec<<"微秒"<<endl;
usleep(sleep_time);
gettimeofday(&tv,NULL);
cout << "usleep after time: " << tv.tv_sec<<"s,"<<tv.tv_usec<<"微秒"<<endl;
}
运行结果
sleep before time: 1560260201
sleep after time: 1560260301
======================
usleep before time: 1560260301
usleep after time: 1560260301
======================
not usleep before time: 1560260301s,491772微秒
not usleep after time: 1560260301s,491948微秒
======================
usleep before time: 1560260301s,491962微秒
usleep after time: 1560260301s,492191微秒
从使用usleep(0)和使用了usleep(100)方法来看,执行前后的时间差差不多相差100,从而可以看出usleep()是以微秒级别为单位的。
到此这篇关于C++ sleep()和usleep()的区别的文章就介绍到这了,更多相关C++ sleep() usleep()内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!