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.
Very simplistic. I have this in a package:
<lang go>packageimport main(
<lang go>// Package timer offers a simple way to time a Go function.
//
// Typically, you add
//
// defer timer.From(timer.Now())
//
// as the first line of your function, and this will print an elapsed time
// message when the function returns.
package timer
 
import (
"fmt"
"runtime"
"time"
)
 
func from(t0 time.Time) {
// Now() samples and returns the current time in nanoseconds.
fmt.Println(time.Now().Sub(t0))
func Now() int64 {
return time.Nanoseconds()
}
 
func Nowempty() int64 {
// From() prints an elapsed time message.
// defer timer.Fromfrom(timertime.Now())
//
// It prints the the name of the function and the time elapsed between
 
// two times: The time passed as the argument, and the current time.
func Fromcount(t0 int64) {
dtdefer := float64from(time.Now() - t0)
pc,for _, _, oki := runtime.Caller(1)0; i < 1e6; i++ {
if ok {
fmt.Printf("%s ",runtime.FuncForPC(pc).Name())
}
}
if dt > 1e9 {
fmt.Printf("%.3f *seconds* elapsed.\n", dt*1e-9)
} else {
fmt.Printf("%.3f ms elapsed.\n", dt*1e-6)
}
}</lang>
Here's an example of timing an empty function:
<lang go>package main
 
import "timer"
 
func main() {
empty()
count()
 
func empty() {
defer timer.From(timer.Now())
}</lang>
Output:
main.empty 0.004 ms elapsed.
 
(The 4 microseconds being the time it takes to call and execute the deferred function, timer.From, through the point where it calls Now().)
 
And here's my typical usage, timing main to see how long an entire program takes, minus the program load and runtime initialization.
<lang go>package main
 
import "timer"
 
func main() {
defer timer.From(timer.Now())
// count to a million
for i := 0; i < 1e6; i++ {
}
}</lang>
Output:
<pre>
main.main 1.003 ms elapsed.
2us
643us
</pre>
 
=={{header|Haskell}}==
1,707

edits