以下の内容はhttps://devlights.hatenablog.com/entry/2025/10/08/073000より取得しました。


Goメモ-625 (特定のベンチマークだけメモリ割当の統計情報を出力)(testing.B.ReportAllocs)

関連記事

GitHub - devlights/blog-summary: ブログ「いろいろ備忘録日記」のまとめ

概要

以下、自分用のメモです。よく忘れるので、ここにメモメモ。。。

ベンチマークでメモリ割当の統計情報を出力したいときがあります。

基本、コマンドラインで

$ go test . -bench . -benchmem

って感じで -benchmem って付ければ良いだけなのですが、このオプションを付与すると全ベンチマークで有効になります。

たまに、特定のベンチマークだけ有効にしたいときもあったりします。

そんなときに、ベンチマーク関数内で testing.B.ReportAllocs メソッドを呼び出しておくと、そのベンチマークだけ有効になります。

サンプル

reportalloc_test.go

package main

import (
    "slices"
    "testing"
)

func voidfn(_ []int) {}

func BenchmarkWithReportAllocs(b *testing.B) {
    src := make([]int, 255)
    for i := range src {
        src[i] = i
    }

    // -benchmem オプションを付与したのと同じことになる
    // オプションとして指定すると全ベンチマークがONとなるが
    // ReportAllocs()の場合は、呼び出したベンチマークのみがONとなる。
    b.ReportAllocs()

    for b.Loop() {
        dst := slices.Clone(src)
        voidfn(dst)
    }
}

func BenchmarkWithoutReportAllocs(b *testing.B) {
    src := make([]int, 255)
    for i := range src {
        src[i] = i
    }

    for b.Loop() {
        dst := append([]int{}, src...)
        voidfn(dst)
    }
}

Taskfile.yml

# https://taskfile.dev

version: '3'

tasks:
  default:
    cmds:
      - go test . -bench .
      - go test . -bench . -benchmem

実行

$ task
task: [default] go test . -bench .
goos: linux
goarch: amd64
pkg: github.com/devlights/try-golang/examples/benchmarks/04.reportalloc
cpu: Intel(R) Core(TM) Ultra 5 125H
BenchmarkWithReportAllocs-18             3909057               310.4 ns/op          2048 B/op          1 allocs/op
BenchmarkWithoutReportAllocs-18          3827202               322.6 ns/op
PASS
ok      github.com/devlights/try-golang/examples/benchmarks/04.reportalloc      2.452s

task: [default] go test . -bench . -benchmem
goos: linux
goarch: amd64
pkg: github.com/devlights/try-golang/examples/benchmarks/04.reportalloc
cpu: Intel(R) Core(TM) Ultra 5 125H
BenchmarkWithReportAllocs-18             3708218               322.0 ns/op          2048 B/op          1 allocs/op
BenchmarkWithoutReportAllocs-18          3210252               338.4 ns/op          2048 B/op          1 allocs/op
PASS
ok      github.com/devlights/try-golang/examples/benchmarks/04.reportalloc      2.285s

-benchmemを付与していない場合でも、testing.B.ReportAllocsを呼び出しているものは統計情報が出力されています。

参考情報

個人的Goのおすすめ書籍

個人的に読んでとても勉強になった書籍さんたちです。


過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。




以上の内容はhttps://devlights.hatenablog.com/entry/2025/10/08/073000より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14