Skip to content

proposal: time: add function to get time.Time for a given monotonic time #23227

@eriksw

Description

@eriksw

What version of Go are you using (go version)?

go version go1.9.2 linux/amd64

What did you expect to see?

A way to construct a time.Time from a value in the system's monotonic time.

(My use case is an integration with systemd: I am given a deadline to respond to a request, and the deadline is given only in terms of CLOCK_MONOTONIC. I want to convert that value to something I can use as a Context's Deadline.)

What did you see instead?

There is no way I could find to accomplish this without resorting to reflect and unsafe.

Workaround (this should not be necessary):

import (
    "reflect"
    "time"
    _ "unsafe"
)

//go:linkname startNano runtime.startNano
var startNano int64

func TimeAtMonotonic(nanos int64) time.Time {
    now := time.Now()
    nowExt := reflect.ValueOf(now).FieldByName("ext").Int()
    return now.Add(time.Duration(nanos - startNano - nowExt))
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions