Time a function: Difference between revisions
m
→Alternative technique: updated for changes in time package, also simplified.
m (→Alternative technique: updated for changes in time package, also simplified.) |
|||
Line 490:
===Alternative technique===
Very simplistic. As the first line of the function you wish to time, use <tt>defer</tt> with an argument of <tt>time.Now()</tt> to print the elapsed time to the return of any function. For example, define the function <tt>from</tt> as shown below. It works because defer evaluates its function's arguments at the time the function is deferred, so the current time gets captured at the point of the defer. When the function containing the defer returns, the deferred <tt>from</tt> function runs, computes the elapsed time as a <tt>time.Duration</tt>, and prints it with standard formatting, which adds a nicely scaled unit suffix.
// defer timer.From(timer.Now())▼
"fmt"
"time"
)
func from(t0 time.Time) {
fmt.Println(time.Now().Sub(t0))
func Now() int64 {▼
}
}▼
func
}
}
▲<lang go>package main
func main() {
empty()
count()
▲}
}</lang>
Output:
<pre>
2us
643us
</pre>
=={{header|Haskell}}==
|