目前,在对 golang 中的一个小函数进行 golang 基准测试时,我得到以下结果
go test -bench=.
输出:
BenchmarkBcrypt10-4 1000000000 0.08 ns/op
BenchmarkBcrypt15-4 1 2607594388 ns/op
BenchmarkBcrypt18-4 1 20472224268 ns/op
PASS
是否有办法将时间单位从 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)
}
还有我的
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)
}
我为您提供完美的解决方案!
安装所需的benchstat工具:
go get golang.org/x/perf/cmd/benchstat
go install golang.org/x/perf/cmd/benchstat
运行基准测试,并将输入输入到 benchstat
go test -bench=. | benchstat -
输出示例:
$ go test -bench=. | benchstat -
name time/op
Bcrypt2-6 0.05ns ± 0%
Bcrypt4-6 0.00ns ± 1%
Bcrypt6-6 0.00ns ± 0%
Bcrypt8-6 0.01ns ± 0%
Bcrypt10-6 0.05ns ± 1%
Bcrypt18-6 11.7s ± 1%
Bcrypt15-6 1.46s ± 0%
修改后的测试文件:
package main
import "testing"
func BenchmarkBcrypt2(b *testing.B) { HashPassword("my pass", 2) }
func BenchmarkBcrypt4(b *testing.B) { HashPassword("my pass", 4) }
func BenchmarkBcrypt6(b *testing.B) { HashPassword("my pass", 6) }
func BenchmarkBcrypt8(b *testing.B) { HashPassword("my pass", 8) }
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) }
一些有用的链接:
乍一看...您可以尝试
fmt.Println(b.Elapsed() / time.Duration(b.N))
解决方法
package main
import (
"fmt"
"testing"
"time"
"gonum.org/v1/gonum/floats"
)
const arraySize = 1000000
func BenchmarkGonumSum(b *testing.B) {
nums := make([]float64, arraySize)
for i := 0; i < arraySize; i++ {
nums[i] = float64(i)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = floats.Sum(nums)
}
fmt.Println("number of iterations: ", b.N)
fmt.Println("elapsed:", b.Elapsed()/time.Duration(b.N))
}
此代码将产生下一个输出
BenchmarkGonumSum
number of iterations: 1
elapsed: 539.783µs
number of iterations: 100
elapsed: 249.077µs
number of iterations: 4816
elapsed: 188.684µs
number of iterations: 6358
elapsed: 184.344µs
BenchmarkGonumSum-12 6358 184345 ns/op
PASS
正如您在大量迭代计数中所看到的,它非常接近标准基准输出