hrtime

hrtime(bool $as_number = false): array|int

高分辨率单调计时:hrtime() 返 [秒, 纳秒] 数组,hrtime(true) 返整数纳秒。单调钟只增不减——NTP 回拨与夏令时只影响墙钟,测代码耗时用它,记时间戳用 microtime。

C C23

C23
#include <stdio.h>
#include <time.h>

int main(void) {
    /* clock_gettime(CLOCK_MONOTONIC) 是 POSIX 原版;墙钟对应 CLOCK_REALTIME */
    struct timespec a, b;
    clock_gettime(CLOCK_MONOTONIC, &a);
    clock_gettime(CLOCK_MONOTONIC, &b);
    while (b.tv_sec < a.tv_sec || (b.tv_sec == a.tv_sec && b.tv_nsec <= a.tv_nsec)) {
        clock_gettime(CLOCK_MONOTONIC, &b); /* 自旋到计数器严格前进 */
    }
    long long diff = (long long)(b.tv_sec - a.tv_sec) * 1000000000LL + (b.tv_nsec - a.tv_nsec);
    printf("diff>0: %s\n", diff > 0 ? "true" : "false");
    printf("ns in range: %s\n", b.tv_nsec >= 0 && b.tv_nsec < 1000000000L ? "true" : "false");
    return 0;
}
输出
diff>0: true
ns in range: true

C++ C++26

C++26
#include <chrono>
#include <cstdio>

int main() {
    // steady_clock 是单调钟;system_clock 是墙钟
    auto a = std::chrono::steady_clock::now();
    auto b = std::chrono::steady_clock::now();
    while (b <= a) {
        b = std::chrono::steady_clock::now(); // 自旋到计数器严格前进
    }
    auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(b - a).count();
    std::printf("diff>0: %s\n", diff > 0 ? "true" : "false");
    std::printf("is steady: %s\n", std::chrono::steady_clock::is_steady ? "true" : "false");
}
输出
diff>0: true
is steady: true

C# v11.0.100

v11.0.100
// Stopwatch.GetTimestamp 读单调计数器;DateTime.Now 是墙钟
using System.Diagnostics;
long a = Stopwatch.GetTimestamp();
long b = Stopwatch.GetTimestamp();
while (b <= a) {
    b = Stopwatch.GetTimestamp(); // 自旋到计数器严格前进
}
Console.WriteLine($"diff>0: {b - a > 0}");
Console.WriteLine($"frequency>0: {Stopwatch.Frequency > 0}");
输出
diff>0: True
frequency>0: True

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"time"
)

func main() {
	// time.Now 内嵌单调钟:NTP/夏令时跳变不会让 Sub/Since 回退
	start := time.Now()
	for time.Since(start) == 0 {
		// 自旋到单调计数器严格前进
	}
	el := time.Since(start)
	fmt.Println("elapsed>0:", el > 0)
	fmt.Println("nanos>0:", el.Nanoseconds() > 0)
}
输出
elapsed>0: true
nanos>0: true

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        // System.nanoTime() 是单调钟;currentTimeMillis() 是墙钟
        long a = System.nanoTime();
        long b = System.nanoTime();
        while (b <= a) {
            b = System.nanoTime(); // 自旋到计数器严格前进
        }
        System.out.println("diff>0: " + (b - a > 0));
        System.out.println("non-negative: " + (b >= 0));
    }
}
输出
diff>0: true
non-negative: true

JavaScript v26.13.1

v26.13.1
// performance.now() 是单调毫秒浮点;Node 另有 process.hrtime
let x = performance.now();
while (performance.now() <= x) {
  // 自旋到时钟严格前进
}
console.log(`performance.now diff>0: ${performance.now() - x > 0}`);
输出
performance.now diff>0: true

PHP v8.6.0

v8.6.0
// hrtime(true) 是单调纳秒计数器——NTP/夏令时校正只影响墙钟
$a = hrtime(true);
$b = hrtime(true);
while ($b <= $a) { $b = hrtime(true); } // 自旋到计数器严格前进
echo "diff>0: ", var_export($b - $a > 0, true), PHP_EOL;
echo "is int: ", var_export(is_int($b), true), PHP_EOL;
$pair = hrtime(); // 自任意纪元以来的 [秒, 纳秒]
echo "array ns in range: ", var_export($pair[1] >= 0 && $pair[1] < 1_000_000_000, true), PHP_EOL;
输出
diff>0: true
is int: true
array ns in range: true

Python v3.15.2

v3.15.2
import time

# perf_counter_ns 是单调纳秒计数器(POSIX 上即 CLOCK_MONOTONIC)
a = time.perf_counter_ns()
b = time.perf_counter_ns()
while b <= a:
    b = time.perf_counter_ns()  # 自旋到计数器严格前进
print(f"diff>0: {b - a > 0}")
print(f"is int: {isinstance(b, int)}")
输出
diff>0: True
is int: True

Rust v1.99.1

v1.99.1
use std::time::Instant;

fn main() {
    // Instant 是单调钟;SystemTime 是墙钟(NTP/夏令时可令其回拨)
    let t0 = Instant::now();
    while t0.elapsed().as_nanos() == 0 {
        // 自旋到计数器严格前进
    }
    let el = t0.elapsed();
    println!("elapsed>0: {}", el.as_nanos() > 0);
    println!("subsec ns in range: {}", el.subsec_nanos() < 1_000_000_000);
}
输出
elapsed>0: true
subsec ns in range: true

TypeScript v26.13.1

v26.13.1
// performance.now() 是单调毫秒浮点;Node 另有 process.hrtime
let x: number = performance.now();
while (performance.now() <= x) {
  // 自旋到时钟严格前进
}
const diff: number = performance.now() - x;
console.log(`performance.now diff>0: ${diff > 0}`);
输出
performance.now diff>0: true

语言差异说明

C:clock_gettime(CLOCK_MONOTONIC)(<time.h>)是 HRTime 的原型;CLOCK_MONOTONIC_RAW 连 NTP 微调都不吃;CLOCK_REALTIME 是墙钟,会被对时回拨。

C++:std::chrono::steady_clock 单调(is_steady == true 是编译期保证),system_clock 挂墙钟;纳秒换算用 duration_cast。

C#:Stopwatch 包 QPC 单调计数器,Stopwatch.Frequency 是刻度频率;DateTime.Now/UtcNow 是墙钟(NTP 回拨会跳)。

Go:time.Now 返回的 Time 内嵌单调读数,进程内 Sub/Since/Until 抗对时跳变;时间戳序列化跨进程后单调部分丢失。

Java:System.nanoTime() 单调纳秒,currentTimeMillis() 墙钟毫秒——两者不可换算;jsr310 Instant.now() 精度取决于系统。

JavaScript:performance.now() 单调毫秒浮点(浏览器与 Node 皆有,perf_hooks 同源);Date.now() 是墙钟毫秒;Node 另有 process.hrtime.bigint() 纳秒。

PHP:hrtime() 返 [秒, 纳秒] 数组,hrtime(true) 返整数纳秒(7.3+);与 microtime(true) 配对——墙钟时刻用 microtime,测代码耗时一律 hrtime(NTP/夏令时回拨不影响);HRTime\PerformanceCounter 是面向对象的同能力封装。

Python:time.perf_counter_ns()(3.7+ 整数纳秒,无浮点精度损失)与 perf_counter();time.monotonic() 同源;time.time() 是墙钟。

Rust:Instant 单调、SystemTime 墙钟;Instant::now().elapsed() 即 HRTime 的典型用法;墙钟日期格式化需 chrono。

TypeScript:同 JavaScript;performance 在 DOM lib 与 Node 全局均可用。