[英]POSIX C/C++ sleep() and usleep() not working? (Raspberry PI)
[英]Linux C++ userspace app real time sleep function (POSIX, Raspberry Pi)
我需要一個以μs掛起程序的函數,它應該是實時的,所以如果我用50μs調用它,那么線程應該停止正好50μs。 我的C ++程序在Raspberry Pi上運行,安裝了普通的Raspbian。
我編寫了這個示例程序,它使用posix時間函數暫停一個度量暫停時間。
#include <cstdlib>
#include "stdint-gcc.h"
#include "signal.h"
#include <time.h>
#include <cerrno>
#include <cstdio>
#include <iostream>
#include <cstring>
#define S_IN_NS 1000000000UL
#define MS_IN_NS 1000000UL
#define US_IN_NS 1000UL
#define GET_TIME_CLOCK CLOCK_MONOTONIC
using namespace std;
int main(int argc, char** argv) {
struct timespec newTimeStamp;
struct timespec oldTimeStamp;
struct timespec sleeptime;
sleeptime.tv_sec = 0;
sleeptime.tv_nsec = 50000; //50us
if (clock_gettime(GET_TIME_CLOCK, &oldTimeStamp) == -1)
cout << "Could not get clock time! ERRNO: " << strerror(errno);
if ((clock_nanosleep(CLOCK_MONOTONIC, 0, &sleeptime, NULL)) == -1)
cout << "Sleep failed! ERRNO: " << strerror(errno);
if (clock_gettime(GET_TIME_CLOCK, &newTimeStamp) == -1)
cout << "Could not get clock time! ERRNO: " << strerror(errno);
uint64_t measuredSec = (newTimeStamp.tv_sec - oldTimeStamp.tv_sec);
int32_t measuredNs = (newTimeStamp.tv_nsec - oldTimeStamp.tv_nsec);
uint64_t diffus = (((measuredSec * S_IN_NS) + measuredNs + 500) / 1000UL);
uint64_t diffns = (((measuredSec * S_IN_NS) + measuredNs));
cout << "Diffns:" << diffns << " Diffus:" << diffus << endl;
return 0;
}
構建命令:
arm-bcm2708hardfp-linux-gnueabi-g++ -lrt -c -g -MMD -MP -MF "build/Debug/GNU_ARM_HARDFP-Linux-x86/main.o.d" -o build/Debug/GNU_ARM_HARDFP-Linux-x86/main.o main.cpp
arm-bcm2708hardfp-linux-gnueabi-g++ -lrt -o dist/Debug/GNU_ARM_HARDFP-Linux-x86/timetest build/Debug/GNU_ARM_HARDFP-Linux-x86/main.o
結果(chrt - 操作進程的實時屬性):
pi@raspberrypi ~ $ sudo chrt 99 ./timetest
Diffns:130994 Diffus:131
pi@raspberrypi ~ $ sudo chrt 99 ./timetest
Diffns:135994 Diffus:136
pi@raspberrypi ~ $ sudo chrt 99 ./timetest
Diffns:138993 Diffus:139
該程序應該睡50天,但我測量130-139us。 如果我將GET_TIME_CLOCK定義更改為CLOCK_PROCESS_CPUTIME_ID,則測量cpu時間(不包括休眠時間)(據我了解)。
結果:
pi@raspberrypi ~ $ sudo chrt 99 ./timetest
Diffns:89000 Diffus:89
pi@raspberrypi ~ $ sudo chrt 99 ./timetest
Diffns:86000 Diffus:86
pi@raspberrypi ~ $ sudo chrt 99 ./timetest
Diffns:88000 Diffus:88
即使我將睡眠時間改為500μs,也需要大約80-90μs來執行clock_nanosleep()函數!
那么有沒有辦法在Raspbian上的C ++用戶空間應用程序中暫停一個線程一段時間(μs)?
謝謝
如果您需要在如此精確的時間內睡眠,您可能需要使用旋轉循環來檢查當前時間。 這將消耗相當多的功率(並產生熱量),但它是一種相當可靠和便攜的方式。 另一個想法是嘗試這個頁面上的想法: http : //blog.regehr.org/archives/794
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.