1.
windows上的sleep最小間隔可以精確到1ms,但是linux上sleep函數需要注意幾個地方:
1,usleep(int microseconds)是舊式API,雖然參數是微妙,但是在linux系統上如果間隔低於10毫秒,死循環的CPU佔用率仍然很高,如果要用usleep,間隔最小值必須設置爲10ms,10000微妙。windows上不存在這種問題,只要sleep的間隔有1ms,死循環CPU佔用率很低。
2,kernel 2.0之後才提供了一個新版API:nanosleep(int microseconds),這個API纔可以將間隔時間控制在微秒級。
參考
http://tldp.org/HOWTO/IO-Port-Programming-4.html
2.
nanosleep的取值限制問題可能導致cpu過高,可參考
https://blog.csdn.net/s_ddwqwd/article/details/82788838
3.
ps -eLo pid,lwp,pcpu |grep pid
配合pstack查找性能問題比較方便
4.
std sleep_for 和 usleep對比,測試結果:
1 67 usleep
2 74 sleep_for
3 62 usleep
4 61 sleep_for
5 60 usleep
6 60 sleep_for
7 60 usleep
8 60 sleep_for
9 61 usleep
10 60 sleep_for
11 62 usleep
12 60 sleep_for
13 60 usleep
14 60 sleep_for
15 60 usleep
16 60 sleep_for
17 60 usleep
18 61 sleep_for
19 61 usleep
20 60 sleep_for
std::this_thread::sleep_for(std::chrono::microseconds(5));
usleep(5);
25 for (int i = 0; i < 10; i++){
26
27 gettimeofday(&tv,&tz);
28 int64_t v = tv.tv_sec * 1000000 + tv.tv_usec;
29
30 usleep(5);
31
32 gettimeofday(&tv1,&tz1);
33 int64_t v1 = tv1.tv_sec * 1000000 + tv1.tv_usec;
34 cout << v1 - v << " usleep" << endl;
35
36 }
沒什麼大的差異,cpu佔用上,sleep_for線程偏高,高於1-幾倍吧,穩定性差,具體原因待分析