Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: time.UnixNow() & time.UnixNowMs() #39837

Closed
oguzyildizz opened this issue Jun 24, 2020 · 6 comments
Closed

proposal: time.UnixNow() & time.UnixNowMs() #39837

oguzyildizz opened this issue Jun 24, 2020 · 6 comments

Comments

@oguzyildizz
Copy link

Hi, in our code we call time.Now() pretty extensively, enough to notice some overhead of calling it. Since we only need the unix timestamp, can we have a way to just get the unix timestamp without allocating unnecessary Time{} structs?

@gopherbot gopherbot added this to the Proposal milestone Jun 24, 2020
@ianlancetaylor
Copy link
Contributor

I suggest that you use https://pkg.go.dev/golang.org/x/sys/unix?tab=doc#Gettimeofday which calls the gettimeofday system call on a Unix system.

@OneOfOne
Copy link
Contributor

OneOfOne commented Jun 24, 2020

Also if you're fine with using unsafe, you can do something like:

package main

import (
	"fmt"
	"time"
	_ "unsafe"
)

//go:linkname timeNow runtime.walltime
func timeNow() (sec int64, nsec int32)

func main() {
	fmt.Println(timeNow())
	t := time.Now()
	fmt.Println(t.Unix(), t.Nanosecond())
}

@oguzyildizz
Copy link
Author

@ianlancetaylor I'm getting 0 result from that, I think it's because of this issue: #38925

@OneOfOne thanks, seems like it's working! anything I should be careful with the unsafe usage?

@ianlancetaylor
Copy link
Contributor

#38925 was fixed, though. What system are you using?

The unsafe suggestion by @OneOfOne is cute but is completely unsafe and unsupported. It will certainly break in some future release of Go.

@oguzyildizz
Copy link
Author

I'm using:

go version go1.13.3 darwin/amd64

Just to check, it returns the unix timestamp, right? Not the "time of day" (e.g. seconds since start of day)

@ianlancetaylor
Copy link
Contributor

Yes, unix.Gettimeofday returns a unix.Timeval with a Sec field that is the number of seconds since the epoch, which is the same number that time.Now().Unix() returns.

@golang golang locked and limited conversation to collaborators Jun 25, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants