目前,当我在 golang 中对一个小函数进行 golang 基准测试时,我得到以下结果
go test -bench=.
Run Code Online (Sandbox Code Playgroud)
输出:
BenchmarkBcrypt10-4 1000000000 0.08 ns/op
BenchmarkBcrypt15-4 1 2607594388 ns/op
BenchmarkBcrypt18-4 1 20472224268 ns/op
PASS
Run Code Online (Sandbox Code Playgroud)
是否有办法将时间单位从 ns 更改为毫秒或秒?
这是我的基准文件 ( bcrypt_test.go
):
package main
import "testing"
func BenchmarkBcrypt10(b *testing.B){
HashPassword("my pass", 10)
}
func BenchmarkBcrypt15(b *testing.B){
HashPassword("my pass", 15)
}
func BenchmarkBcrypt18(b *testing.B){
HashPassword("my pass", 18)
}
Run Code Online (Sandbox Code Playgroud)
和我的main.go
:
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
func HashPassword(password string, cost int) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), cost)
return string(bytes), err
}
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
func main() {
password := "secret"
hash, _ := HashPassword(password, 12) // ignore error for the sake of simplicity
fmt.Println("Password:", password)
fmt.Println("Hash: ", hash)
match := CheckPasswordHash(password, hash)
fmt.Println("Match: ", match)
}
Run Code Online (Sandbox Code Playgroud)
我为您提供完美的解决方案!
\n安装所需的 benchstat 工具:
\ngo get golang.org/x/perf/cmd/benchstat\ngo install golang.org/x/perf/cmd/benchstat\n
Run Code Online (Sandbox Code Playgroud)\n生成文件:
\ngather: ; time go test -bench=. | grep --line-buffered ^Bench | tee -a /tmp/o\nstats: ; benchstat /tmp/o\n
Run Code Online (Sandbox Code Playgroud)\n当然,您不需要使用 makefile。如果您愿意,只需直接在 shell 中运行命令即可。
\ngo test -bench=. >/tmp/o\nbenchstat /tmp/o\n
Run Code Online (Sandbox Code Playgroud)\n示例输出:
\n$ make gather stats \ntime go test -bench=. | grep --line-buffered ^Bench | tee -a /tmp/o\nBenchmarkBcrypt2-6 1000000000 0.04578 ns/op\nBenchmarkBcrypt4-6 1000000000 0.0007562 ns/op\nBenchmarkBcrypt6-6 1000000000 0.002905 ns/op\nBenchmarkBcrypt8-6 1000000000 0.01147 ns/op\nBenchmarkBcrypt10-6 1000000000 0.04584 ns/op\nBenchmarkBcrypt15-6 1 1462752100 ns/op\nBenchmarkBcrypt18-6 1 11705497684 ns/op\ntime: Real 0m14.1s User 0m14.1s System 0m0.0s\nbenchstat /tmp/o\nname time/op\nBcrypt2-6 0.05ns \xc2\xb1 0%\nBcrypt4-6 0.00ns \xc2\xb1 1%\nBcrypt6-6 0.00ns \xc2\xb1 0%\nBcrypt8-6 0.01ns \xc2\xb1 0%\nBcrypt10-6 0.05ns \xc2\xb1 1%\nBcrypt18-6 11.7s \xc2\xb1 1%\nBcrypt15-6 1.46s \xc2\xb1 0%\n
Run Code Online (Sandbox Code Playgroud)\n修改后的测试文件:
\ngo get golang.org/x/perf/cmd/benchstat\ngo install golang.org/x/perf/cmd/benchstat\n
Run Code Online (Sandbox Code Playgroud)\n一些有用的链接:
\n