获取单调时间,同CLOCK_MONOTONIC

Get monotonic time, same as CLOCK_MONOTONIC

如何在 Go 中获取以纳秒为单位的启动单调时间?我需要与以下 C 代码 return:

相同的值
static unsigned long get_nsecs(void)
{
    struct timespec ts;

    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec * 1000000000UL + ts.tv_nsec;
}

time 包中的函数似乎 return 当前时间 and/or 日期。

将 Go 与 cgo 一起使用。

使用unsigned long long保证纳秒的64位整数值。例如,在 Windows 上,unsigned long 是一个 32 位整数值。

monotonic.go:

package main

import "fmt"

/*
#include <time.h>
static unsigned long long get_nsecs(void)
{
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return (unsigned long long)ts.tv_sec * 1000000000UL + ts.tv_nsec;
}
*/
import "C"

func main() {
    monotonic := uint64(C.get_nsecs())
    fmt.Println(monotonic)
}

$ go run monotonic.go
10675342462493
$