获取单调时间,与CLOCK_MONOTONIC相同

问题描述 投票:0回答:2

如何在 Go 中获得从启动到纳秒的单调时间?我需要与以下 C 代码返回的值相同的值:

static unsigned long get_nsecs(void)
{
    struct timespec ts;

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

time
包中的函数似乎返回当前时间和/或日期。

go time clock
2个回答
4
投票

将 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
$ 

0
投票

您可以使用系统调用包。

import (
    "syscall"
    "unsafe"
)

func getNSecs() int64 {
    var ts syscall.Timespec
    syscall.Syscall(syscall.SYS_CLOCK_GETTIME, 4, uintptr(unsafe.Pointer(&ts)), 0)
    return ts.Sec*1e9 + ts.Nsec
}
© www.soinside.com 2019 - 2024. All rights reserved.