[問題] 如何暫停microsecond等級的時間?
看板C_and_CPP (C/C++)作者liataian (T-PANY FOREVER)時間11年前 (2015/02/15 16:43)推噓4(4推 0噓 31→)留言35則, 6人參與討論串1/1
各位版友好,有些關於時間方面的問題想請教大家一下
最近在用c++寫簡單的socket程式,內容為Client端每隔幾秒要傳資料給Server端這樣
因為要做研究的關係,我想知道Client每隔1秒或是每隔1.000010秒傳資料給Server
對於我們想知道的結果會有什麼影響, 但是這就是會遇到問題了
就我這幾天網上查的結果, 似乎沒有任何一個function可以達到microsecond等級的暫停
即使我用usleep(1000010)也沒辦法精確的暫停1.000010秒
畢竟系統呼叫usleep()這個function似乎就要1ms到2ms的時間了(?)
對於usleep()我是這樣計算時間的:
#include <iostream>
#include <sys/time.h>
using namespace std;
int main(){
timeval t1, t2;
double elapsedTime;
gettimeofday(&t1, NULL);
usleep(1000010); //睡1.000010秒
gettimeofday(&t2, NULL);
elapsedTime = (t2.tv_sec - t1.tv_sec);
elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000000.0;
cout << elapsedTime << " seconds.\n";
return 0;
}
嘗試多次的結果, elapsedTime還是會比預期多1ms到2ms
不知道這跟系統的timer resolution有沒有關係?
我在MAC OSX上用以下的code所測到timer resolution為3~5 microsecond左右
#include <iostream>
#include <ctime>
#include <unistd.h>
using namespace std;
int main()
{
clock_t t1, t2;
t1 = t2 = clock();
// loop until t2 gets a different value
while(t1 == t2){
t2 = clock();
}
// print resolution of clock()
cout << (double)(t2 - t1) / CLOCKS_PER_SEC * 1000000.0 << " us.\n";
return 0;
}
對於暫停microsecond等級的時間版友有任何想法可以提點一下嗎?
先謝謝各位!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 203.73.50.125
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1423989836.A.3D3.html
推
02/15 16:47, , 1F
02/15 16:47, 1F
推
02/15 17:28, , 2F
02/15 17:28, 2F
→
02/15 17:30, , 3F
02/15 17:30, 3F
→
02/15 17:31, , 4F
02/15 17:31, 4F
→
02/15 17:31, , 5F
02/15 17:31, 5F
→
02/15 17:32, , 6F
02/15 17:32, 6F
→
02/15 17:32, , 7F
02/15 17:32, 7F
→
02/15 17:34, , 8F
02/15 17:34, 8F
→
02/15 17:35, , 9F
02/15 17:35, 9F
→
02/15 17:35, , 10F
02/15 17:35, 10F
→
02/15 17:36, , 11F
02/15 17:36, 11F
→
02/15 19:47, , 12F
02/15 19:47, 12F
→
02/15 19:48, , 13F
02/15 19:48, 13F
→
02/16 00:58, , 14F
02/16 00:58, 14F
→
02/19 16:33, , 15F
02/19 16:33, 15F
推
02/19 22:36, , 16F
02/19 22:36, 16F
→
02/20 15:51, , 17F
02/20 15:51, 17F
→
02/20 17:39, , 18F
02/20 17:39, 18F
→
02/20 17:39, , 19F
02/20 17:39, 19F
→
02/20 17:40, , 20F
02/20 17:40, 20F
→
02/20 17:40, , 21F
02/20 17:40, 21F
推
02/20 20:21, , 22F
02/20 20:21, 22F
→
02/20 20:23, , 23F
02/20 20:23, 23F
→
02/20 20:23, , 24F
02/20 20:23, 24F
→
02/20 20:24, , 25F
02/20 20:24, 25F
→
02/20 20:26, , 26F
02/20 20:26, 26F
→
02/20 20:26, , 27F
02/20 20:26, 27F
→
02/20 20:33, , 28F
02/20 20:33, 28F
→
02/20 20:54, , 29F
02/20 20:54, 29F
→
02/20 20:55, , 30F
02/20 20:55, 30F
→
02/20 20:57, , 31F
02/20 20:57, 31F
→
02/20 20:57, , 32F
02/20 20:57, 32F
→
02/21 00:03, , 33F
02/21 00:03, 33F
→
02/21 00:03, , 34F
02/21 00:03, 34F
→
02/21 00:04, , 35F
02/21 00:04, 35F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章