Search code examples
gotimeclock

Get monotonic time, same as CLOCK_MONOTONIC


How can I get the monotonic time from boot in nanoseconds in Go? I need the same value that the following C code would return:

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

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

The functions in the time package seem to return the current time and/or date.


Solution

  • Use Go with cgo.

    Use unsigned long long to guarantee a 64-bit integer value for nanoseconds. For example, on Windows, unsigned long is a 32-bit integer value.

    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
    $