我如何在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中获得以纳秒为单位的单调启动时间?我需要与以下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 with 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
$