Python:
with Timer() as t :
// TODO a lot
print "scan all disks,cost:%s secs" % t.secs
Now,how to use golang
to achieve this?
I had google this but I can not find any answers I want.
Why am I post my questions in here and then got downvote?
Thank you your help!!!
You can write a function that accepts a function, runs it and prints the time:
import (
"time"
"fmt"
)
func TimeIt(f func(), description string) {
start := time.Now()
f()
fmt.Printf("Running %s took %v
", description, time.Since(start))
}
And then trigger it like so:
func main() {
TimeIt(doSomething, "Doing something")
}
Or just sprinkle it on pieces of code as a closure:
TimeIt(func() {
do()
some()
stuff()
},
"whatever")
Another way to do this in go is to define a timer function and use the defer statement to call it when the function returns.
package main
import (
"fmt"
"time"
)
func timer(start time.Time, description string) {
fmt.Printf("%s took %s
", description, time.Since(start))
}
func main() {
func() {
defer timer(time.Now(), "scan all disks")
// TODO: alot
}()
// OUTPUT: scan all disks took 0s
}
You can measure the time of specific commands by wrapping them into an anonymous function (see above) or you measure the time of a function by simply putting the defer statement at its top, e.g.
func foo() {
defer timer(time.Now(), "foo")
// ...
}
// OUTPUT: foo took 0s