How do you time a function in Go and return its runtime in milliseconds?
相关问题
- Golang mongodb aggregation
- How to flatten out a nested json structure in go
- How to account for clock offsets in a distributed
- how to install private repo using glide golang
- How to convert a string to a byte array which is c
相关文章
- Can I run a single test in a suite?
- How to check if a request was cancelled
- Is it possible to implement an interface with unex
- How to access value of first index of array in Go
- Embedded Interface
- Get POSIX epoch as system_clock::time_point
- How to represent an array with mixed types
- go tutorial select statement
There are several options for timestamping and timers in the time package. See the documentation here: http://golang.org/pkg/time/
Perhaps you can also use a Duration (elapsed) for this...looks a little bit nicer.
Use the Go
testing
package to benchmark the function. For example,Output:
You can also use the Go gotest command to run benchmarks.
Go's
defer
makes this trivial.In Go 1.x, define the following functions:
After that, you get Squeaky Clean one line elapsed time log messages:
The clever magic is that the trace() is called at the beginning of the function, but the un() is deferred to the end. It's not atomic-clock accurate, due to the log statements, but if you need more accuracy, this kind of pattern is one of Go's marshmallowy good strengths.
EDIT:
This answer originally used legacy time package API. Reproduced here for historical value only:
For use w/ Go versions prior to 12-01-2011 weekly:
Another easy way can be:
which will output something like
359.684612ms