我是靠谱客的博主 曾经芹菜,这篇文章主要介绍Linux平台C++ 实现毫秒/微妙级时间获取或者延时,现在分享给大家,希望可以做个参考。

1. 微妙级时间获取

所用头文件

//c++11日期和时间库:chrono

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <chrono> using namespace std::chrono; chrono::system_clock::time_point start_time, end_time; // start_time = chrono::system_clock::now(); // some program end_time = chrono::system_clock::now(); auto dura = (duration_cast<microseconds>(end_time - start_time)).count(); cout << "耗时(time): " << dura << " μs" << endl;

其中"microseconds" 可以换为"milliseconds" 可以获取毫秒

2. 延时

所用头文件 #include <time.h>

复制代码
1
2
3
4
5
6
7
8
9
10
#include <time.h> /* 毫秒级 延时 */ void Sleep(int ms) { struct timeval delay; delay.tv_sec = 0; delay.tv_usec = ms * 1000; // 20 ms select(0, NULL, NULL, NULL, &delay); }

其中输入参数为ms , 如果做微妙级延时,可将"ms * 1000" -> “ms”

3. 综合测试

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <chrono> #include <time.h> #include <iostream> using namespace std; using namespace std::chrono; /* 毫秒级 延时 */ void Sleep(int ms) { struct timeval delay; delay.tv_sec = 0; delay.tv_usec = ms * 1000; // 20 ms select(0, NULL, NULL, NULL, &delay); } int main() { chrono::system_clock::time_point start_time; start_time = chrono::system_clock::now(); Sleep(1000); auto show_time = chrono::system_clock::now(); auto dura = (duration_cast<milliseconds>(show_time - start_time)).count(); cout << "延时:"<< dura <<"ms" <<endl; } // 输出: [ 延时:1000ms]

最后

以上就是曾经芹菜最近收集整理的关于Linux平台C++ 实现毫秒/微妙级时间获取或者延时的全部内容,更多相关Linux平台C++内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(90)

评论列表共有 0 条评论

立即
投稿
返回
顶部