Time a function: Difference between revisions

→‎{{header|Go}}: added standard technique
m (→‎{{header|Euphoria}}: oops brackets missing)
(→‎{{header|Go}}: added standard technique)
Line 335:
 
=={{header|Go}}==
'''Gotest'''
Just clock time, not CPU time. I have this in a package:
 
Go has a standard command for benchmarking, gotest, which can time a function. Given a package with functions,
<lang go>package empty
 
func Empty() {}
 
func Count() {
// count to a million
for i := 0; i < 1e6; i++ {
}
}</lang>
the following code will time them:
<lang go>package empty
 
import "testing"
 
func BenchmarkEmpty(b *testing.B) {
for i := 0; i < b.N; i++ {
Empty()
}
}
 
func BenchmarkCount(b *testing.B) {
for i := 0; i < b.N; i++ {
Count()
}
}</lang>
Gotest varies b.N to get meaningful resolution.
Example:
<pre>
$ gotest -bench=".+"
rm -f _test/pal.a
8g -o _gotest_.8 empty.go empty_test.go
rm -f _test/pal.a
gopack grc _test/pal.a _gotest_.8
testing: warning: no tests to run
PASS
empty.BenchmarkEmpty 100000000 14 ns/op
empty.BenchmarkCount 1000 1002840 ns/op
</pre>
Gotest is the preferred technique when you wish to communicate results to other Go programmers because the output format and benchmarking technique will be known to them.
 
'''Alternative technique'''
 
JustVery clock time, not CPU timesimplistic. I have this in a package:
<lang go>// Package timer offers a simple way to time a Go function.
//
Line 387 ⟶ 432:
Output:
<pre>
main.empty 0.002004 ms elapsed.
</pre>
(The 24 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.
Line 398 ⟶ 443:
func main() {
defer timer.From(timer.Now())
// count to a billionmillion
for i := 0; i < 1e91e6; i++ {
}
}</lang>
Output:
<pre>
main.main 3821.722003 ms elapsed.
</pre>
 
1,707

edits