【问题标题】:Am I doing execution timing measurement in Go in a useful way?我是否以有用的方式在 Go 中进行执行时间测量?
【发布时间】:2019-11-27 16:32:17
【问题描述】:

我的代码:

        // repeat fib(n) 10000 times
        i := 10000
        var total_time time.Duration
        for i > 0 {

            // do fib(n) -> f0
            start := time.Now()
            for n > 0 {
                f0, f1, n = f1, f0.Add(f0, f1), n-1
            }
            total_time = total_time + time.Since(start)

            i--
        }

        // and divide total execution time by 10000
        var normalized_time = total_time / 10000
        fmt.Println(normalized_time)

我看到的执行时间非常短,以至于我怀疑我所做的没有用。如果错了,我做错了什么,我该如何改正?

【问题讨论】:

  • n 初始化为什么?
  • 用户从控制台输入的整数。
  • 好吧,这不是进行基准测试的理想方式。阅读上面链接的博客以了解正确的方法。
  • 使用testing 包中内置的基准测试系统进行基准测试。

标签: go timing


【解决方案1】:

我做错了什么,我该如何改正?


使用 Go testing 包进行基准测试。例如:


在您的代码中将斐波那契数计算作为函数编写。

fibonacci.go:

package main

import "fmt"

// fibonacci returns the Fibonacci number for 0 <= n <= 92.
// OEIS: A000045: Fibonacci numbers:
// F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.
func fibonacci(n int) int64 {
    if n < 0 {
        panic("n < 0")
    }
    f := int64(0)
    a, b := int64(0), int64(1)
    for i := 0; i <= n; i++ {
        if a < 0 {
            panic("overflow")
        }
        f, a, b = a, b, a+b
    }
    return f
}

func main() {
    for _, n := range []int{0, 1, 2, 3, 90, 91, 92} {
        fmt.Printf("%-2d  %d\n", n, fibonacci(n))
    }
}

游乐场:https://play.golang.org/p/FFdG4RlNpUZ

输出:

$ go run fibonacci.go
0   0
1   1
2   1
3   2
90  2880067194370816120
91  4660046610375530309
92  7540113804746346429
$

使用 Go testing 包编写和运行一些基准测试。

fibonacci_test.go:

package main

import "testing"

func BenchmarkFibonacciN0(b *testing.B) {
    for i := 0; i < b.N; i++ {
        fibonacci(0)
    }
}

func BenchmarkFibonacciN92(b *testing.B) {
    for i := 0; i < b.N; i++ {
        fibonacci(92)
    }
}

输出:

$ go test fibonacci.go fibonacci_test.go -bench=. -benchmem
goos: linux
goarch: amd64
BenchmarkFibonacciN0-4     367003574    3.25 ns/op   0 B/op   0 allocs/op
BenchmarkFibonacciN92-4     17369262   63.0 ns/op    0 B/op   0 allocs/op
$ 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    • 2012-06-16
    • 2016-03-01
    • 1970-01-01
    相关资源
    最近更新 更多