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
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.
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)
}
You can just use following code to get current time milliseconds after 1 Jun 1970
time.Now().UnixNano()%1e6/1e3
精彩评论