Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 閏秒 導致程序回應變慢:偵測與緩解方案 (ntpd slew mode)

編輯:關於 Linux

每隔數年插入一個閏秒 會觸發 NTP 客戶端與核心時間同步機制,導致高併發 Java/Go 服務出現 CPU 飆升、延遲暴增。本文提供三步驟偵測腳本與四步驟緩解流程,核心在於啟用 ntpd -x (slew mode) 平滑修正時間跳躍。

閏秒影響示意圖

偵測是否即將發生閏秒

# 1. 查詢 NTP 關聯狀態
ntpq -c "lassoc" -c "mrv &1 &999 leap,srcadr,stratum"
# 若輸出含 leap=01 → 將有閏秒

# 2. 檢查時區檔案
file /etc/localtime
# 若含 "no leap seconds" → 無閏秒

# 3. 核心時間狀態
ntptime | egrep 'INS|DEL'
# 有輸出 → 核心已插入/刪除閏秒標記

緩解流程 (生產環境建議提前執行)

  1. 停止 NTP 服務:systemctl stop ntpd (或 chronyd)。
  2. 重置核心時間狀態:ntptime -s 0 -f 0。
  3. 編輯 /etc/sysconfig/ntpd,在 OPTIONS 加入 -x:
    OPTIONS="-u ntp:ntp -p /var/run/ntpd.pid -g -x"。
  4. 啟動 NTP 服務:systemctl start ntpd。

原理說明

  • 預設 ntpd 遇到閏秒會階梯式調整 (step),導致時間倒退/前進 1 秒,觸發 `timerfd`、`futex` 等系統呼叫大量喚醒。
  • -x (slew mode) 以頻率微調方式在約 2000 秒內平滑吸收 1 秒差異,避免時間跳躍。

壓力測試 C 程式 (驗證核心行為)

/* leap_test.c */
#include 
#include 
int main() {
    struct timespec ts;
    while (1) {
        clock_gettime(CLOCK_REALTIME, &ts);
        printf("%ld.%09ld\n", ts.tv_sec, ts.tv_nsec);
        usleep(100000);
    }
}

編譯執行觀察時間是否出現倒退或跳躍。啟用 slew mode 後曲線應平滑無突變。

Copyright © Windows教程網 All Rights Reserved