brianoh
brianoh

Reputation: 3577

Go - time - milliseconds

I need the time in milliseconds for what could be a large volume of transactions, so I want something that is correct, and fast. Will the following work and do the job best? :


    iMilli  := int((time.Nanoseconds() % 1e6) / 1e3)

TIA

Upvotes: 5

Views: 13812

Answers (3)

olyanren
olyanren

Reputation: 1458

You can just use following code to get current time milliseconds after 1 Jun 1970

time.Now().UnixNano()%1e6/1e3

Upvotes: 2

laslowh
laslowh

Reputation: 8624

EDIT: Since this answer was first written, escape analysis code has been added to the Go compilers. This allows the compiler to avoid unnecessary allocations in certain situations, including (probably) the one described below. With the latest weeklies, therefore, it may be just as good to use a more straightforward call to time.Nanoseconds(). Please do your own profiling.

Most of the time functions cause a heap allocation (that then subsequently needs to be collected, causing a pause in your application). So if you're looking up the time frequently, which it sounds like you are, you'll need to use syscall.Gettimeofday() directly (it's the function that the other time functions end up calling anyway). See the discussion here for more information:

http://groups.google.com/group/golang-nuts/browse_thread/thread/f2209022f43efcca?pli=1

The solution I'm using is to pre-allocate a tv syscall.Timeval, and each time through my inner loop I do this:

syscall.Gettimeofday(&tv)

You can then get the milliseconds with:

(int64(tv.Sec)*1e3 + int64(tv.Usec)/1e3)

I've found this to perform a lot better than calling time.Nanoseconds() or one of the other higher-level time functions.

Upvotes: 7

Lyke
Lyke

Reputation: 4705

There's 1e9 nanoseconds in a second, and 1e6 nanoseconds in a millisecond, so you'd do something like this:

func getTimeString() string {
    now := time.Nanoseconds()
    localTime := time.SecondsToLocalTime(now/1e9)
    miliSeconds := (now % 1e9) / 1e6
    return fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d.%03d",localTime.Year,localTime.Month,localTime.Day,localTime.Hour,localTime.Minute,localTime.Second,miliSeconds)
}

Upvotes: 3

Related Questions