Time a function: Difference between revisions
Content deleted Content added
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'''
<lang go>// Package timer offers a simple way to time a Go function.
//
Line 387 ⟶ 432:
Output:
<pre>
main.empty 0.
</pre>
(The
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
for i := 0; i <
}
}</lang>
Output:
<pre>
main.main
</pre>
|