0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Go言語で自身が使用しているリソースを表示する方法

Last updated at Posted at 2026-01-15

サーバータスクなどで、自身が使用しているCPU使用率やメモリ使用量を定期的にログに出力したい場合があります。 以下のコードは、Go言語で自身のプロセスのCPU使用率とメモリ使用量を取得し、定期的にログに出力する方法を示しています。

自信のプロセス情報を取得するために、gopsutilライブラリを使用しています。

ドキュメント: gopsutil package - github.com/shirou/gopsutil/v4 - Go Packages

以下のコード例では、2秒ごとにCPU使用率とメモリ使用量をログに出力し、メインの処理として重い計算を行う関数を呼び出しています。

go get github.com/shirou/gopsutil/v4/process
package main

import (
	"log"
	"os"
	"time"

	"github.com/shirou/gopsutil/v4/process"
)

func main() {
	// 別のゴルーチンでモニタリングを開始
	go monitorSelf(2 * time.Second)

	// --- ここからメインの処理 ---
	log.Println("Main task started...")

	// 負荷のシミュレーション
	for i := 0; i < 5; i++ {
		heavyCalculation()
		time.Sleep(1 * time.Second)
		log.Println("Do! ", i)
	}

	log.Println("Main task finished.")
}

// monitorSelf は現在のプロセスのCPU使用率とメモリ使用量を指定された間隔でモニタリングします。
func monitorSelf(interval time.Duration) {
	// 自身のプロセスを取得
	pid := int32(os.Getpid())
	p, err := process.NewProcess(pid)
	if err != nil {
		log.Printf("Monitor error: %v", err)
		return
	}

	ticker := time.NewTicker(interval)
	defer ticker.Stop()

	for range ticker.C {
		// CPU使用率(前回の計測からの増分%)
		// 引数が0の場合、前回呼び出し時からの経過時間を使って計算される
		cpuPercent, err := p.Percent(0)
		if err != nil {
			continue
		}

		// メモリ使用量(RSS: 実際に物理メモリを使用しているサイズ)
		memInfo, err := p.MemoryInfo()
		if err != nil {
			continue
		}

		// ログ出力 (MB単位などで整形)
		log.Printf("[MONITOR] CPU: %.2f%% | Mem: %.2f MB", cpuPercent, float64(memInfo.RSS)/1024/1024)
	}
}

// heavyCalculation は非常に大きな範囲で計算を繰り返す重い処理を実行します。
// 主に負荷テストや処理性能の検証目的で使用されます。
func heavyCalculation() {
	// ひたすらループ
	x := 0
	for i := range int(1e11) {
		x += i
	}
	log.Println("heavyCalculation done.", x)
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?