簡體   English   中英

將linux時間設置為毫秒精度

[英]Set linux time to millisecond precision

我有一個嵌入式Linux設備,通過串行通信協議與另一個“主”設備連接。 主設備定期將其日期傳遞給從設備,因為稍后從設備將向主設備返回需要准確加時間戳的信息。 但是,Linux'date'命令僅將系統日期設置為第二精度。 這對我們的用途來說還不夠。

有誰知道如何設置Linux機器的時間比1秒鍾更精確?

其他答案中給出的settimeofday(2)方法存在嚴重問題:它完全按照您的意思執行。 :)

直接改變系統時間的問題在於,如果調整結果為負,它可能會混淆在變更之前和之后獲得時間的程序。 也就是說,他們可以感知時間倒退。

對此的修復是adjtime(3) ,它簡單易用,或者adjtimex(2) ,它復雜,功能強大且特定於Linux。 這兩個調用都使用復雜的算法在一段時間內緩慢調整系統時間,僅向前調整,直到達到所需的更改。

順便問一下,你確定你不是在這里重新發明 輪子嗎? 我建議您閱讀Julien Ridoux和Darryl Veitch的ACM Queue論文“互聯網上的穩健時序原理” 你正在研究嵌入式系統,所以我希望圖5中的振鈴可以讓你感到寒冷。 你能說“阻尼振盪器嗎?” adjtime()adjtimex()使用這個麻煩的算法,所以在某種意義上我反對我自己的建議,但Mills算法仍然比步調整非算法更好。 如果您選擇實施RADclock,那就更好了。

settimeofday()系統調用采用並使用微秒精度。 你將不得不編寫一個簡短的程序來使用它,但這非常簡單。

struct timeval tv;
tv .tv_sec = (some time_t value)
tv .tv_usec = (the number of microseconds after the second)
int rc = settimeofday (&tv, NULL);
if (rc)
        errormessage ("error %d setting system time", errno);
  • 您可以使用settimeofday(2)系統調用; 該接口支持微秒級分辨率。

     #include <sys/time.h> int gettimeofday(struct timeval *tv, struct timezone *tz); int settimeofday(const struct timeval *tv, const struct timezone *tz); struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ }; 
  • 您可以使用clock_settime(2)系統調用; 接口提供多個時鍾,接口支持納秒級分辨率。

     #include <time.h> int clock_getres(clockid_t clk_id, struct timespec *res); int clock_gettime(clockid_t clk_id, struct timespec *tp); int clock_settime(clockid_t clk_id, const struct timespec *tp); struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; CLOCK_REALTIME System-wide real-time clock. Setting this clock requires appropriate privileges. CLOCK_MONOTONIC Clock that cannot be set and represents monotonic time since some unspecified starting point. CLOCK_MONOTONIC_RAW (since Linux 2.6.28; Linux-specific) Similar to CLOCK_MONOTONIC, but provides access to a raw hardware-based time that is not subject to NTP adjustments. CLOCK_PROCESS_CPUTIME_ID High-resolution per-process timer from the CPU. CLOCK_THREAD_CPUTIME_ID Thread-specific CPU-time clock. 

    這個接口提供了clock_getres(2)調用的clock_getres(2) ,它可以准確地告訴你分辨率什么 - 只是因為接口接受納秒並不意味着它實際上可以支持納秒分辨率。 (我有一個模糊的內存,20 ns是關於許多系統的限制,但沒有參考支持這個。)

如果您通過串行鏈路運行支持IP的網絡協議(例如,ooh,PPP),您可以在“主”主機上運行ntpd,然后在嵌入式設備上使用ntpd或ntpdate同步時間。 NTP會照顧你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM