Files

39 lines
1.6 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* monotonic_test.c — 宿主验证 ncm_now_ms(REALTIME) 与 ncm_monotonic_ms(MONOTONIC)。
* 演示:用墙钟算 deadline 在「NTP 拨钟回退 Δ」时,(deadline-now) 被放大成巨大 rem;
* 用单调钟则不受影响(每次至多等剩余 deadline)。
*/
#include "ncm.h"
#include "ncm_common.h"
#include <stdio.h>
#include <unistd.h>
int main(void) {
int64_t w0 = ncm_now_ms();
int64_t m0 = ncm_monotonic_ms();
usleep(50 * 1000);
int64_t w1 = ncm_now_ms();
int64_t m1 = ncm_monotonic_ms();
printf("REALTIME advance: %lld ms\n", (long long)(w1 - w0));
printf("MONOTONIC advance: %lld ms\n", (long long)(m1 - m0));
if (w1 <= w0 || m1 <= m0) { printf("FAIL: clock not advancing\n"); return 1; }
/* 模拟 NTP 把墙钟拨回 Δ=6h 后,(deadline-now) 的变化 */
int64_t base_w = w0;
int64_t base_m = m0;
int64_t tmo = 15000;
int64_t dline_w = base_w + tmo, dline_m = base_m + tmo;
int64_t jump = 6 * 3600 * 1000; /* 拨回 6 小时 */
/* REALTIME:now 回退 jump → rem 巨大 */
int64_t now_w = base_w - jump;
uint32_t rem_w = (uint32_t)(dline_w - now_w);
/* MONOTONIC:now 不受跳变影响 */
int64_t now_m = base_m;
uint32_t rem_m = (uint32_t)(dline_m - now_m);
printf("REALTIME rem after -6h jump = %u ms (%.1f h)\n", rem_w, rem_w / 3600000.0);
printf("MONOTONIC rem after -6h jump = %u ms (%.2f s)\n", rem_m, rem_m / 1000.0);
if (rem_w > rem_m) printf("OK: REALTIME overflow confirmed, MONOTONIC unaffected\n");
else { printf("FAIL: expected REALTIME rem to blow up\n"); return 1; }
return 0;
}