时间单位

英文 中文 单位 换算
seconds s 1秒
milliseconds 毫秒 ms 1/1000 秒
microseconds 微秒 us 1/1000 000 秒
nanosecond 纳秒 ns 1/1000 000 000 秒
picosecond 皮秒 ps 1/1000 000 000 000 秒

Sleep 方案

方案 性质 精度 说明
sleep libc库函数 win 不支持
usleep libc库函数 微秒 已废弃,使用 nanosleep 替代
nanosleep 系统调用 纳秒
poll 系统调用 毫秒
select 系统调用 微秒
sleep_for std::thread 微秒 C++ 11 支持
condition pthread 毫秒 可中断

Sleep 实现

sleep_for

1
2
3
4
5
6
7
#include <thread>

bool sleep_us_c11(long long usec)
{
std::this_thread::sleep_for(std::chrono::microseconds(usec));
return true;
}

nanosleep

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <sys/time.h>

bool sleep_us_nano(long long usec)
{
// POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
// so we use nanosleep() even though it has greater precision than necessary.
struct timespec ts;
ts.tv_sec = usec / 1000000;
ts.tv_nsec = (usec % 1000000) * 1000;
int err = nanosleep(&ts, NULL);
if (err != 0)
{
printf("sleep_us_nano error:%d \n", err);
return false;
}

return true;
}

select

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <pthread.h>
#include <sys/time.h>

bool sleep_us_select(long long usec)
{
struct timeval tv;
tv.tv_sec = usec/1000000;
tv.tv_usec = usec%1000000;

int ret = 0;
do{
ret = select(0,NULL,NULL,NULL,&tv);
}while(ret < 0 && errno == EINTR);

if (ret != 0)
{
printf("sleep_us_select error:%d \n", ret);
return false;
}

return true;
}

poll

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
26
27
28
#include <thread>

bool sleep_us_poll(long long usec)
{
int ms = usec/1000;
if (ms == 0)
{
printf("ms is 0 \n");
ms = 10;
}

int ret = poll(NULL, 0, ms);

if (ret > 0)
{
printf("sleep_us_poll ret:%d \n", ret);
return true;
}
else if(ret == 0)
{
return true;
}
else
{
printf("sleep_us_poll error:%d \n", errno);
return false;
}
}

condition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <thread>

bool sleep_us_condition(long long usec)
{
int ms = usec/1000;
if (ms == 0)
{
printf("ms is 0 \n");
ms = 10;
}

mCond.TimeWait(ms);
return true;
}

英文单位

英文 中文 数字
hundred 100
thousand 1000
million 百萬 1000 000
billion 十億 1000 000 000
trillion 1000 000 000 000
# 参考文献

https://cloud.tencent.com/developer/article/1399240