Skip to content

Add psutil/mem/vmem #918

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/psutil/mem/vmem/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
app
14 changes: 14 additions & 0 deletions examples/psutil/mem/vmem/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# これは何?

[gopsutil](https://github.com/shirou/gopsutil)を用いてメモリ消費量を取得するサンプルです。

```sh
$ task
task: [build] go build -o app main.go
task: [run] ./app
07:25:17 Total=7938MB Used=1569MB Free= 417MB
07:25:18 Total=7938MB Used=1722MB Free= 264MB
07:25:19 Total=7938MB Used=1850MB Free= 187MB
07:25:20 Total=7938MB Used=1886MB Free= 151MB
07:25:21 Total=7938MB Used=1886MB Free= 151MB
```
15 changes: 15 additions & 0 deletions examples/psutil/mem/vmem/Taskfile.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# https://taskfile.dev

version: '3'

tasks:
default:
cmds:
- task: build
- task: run
build:
cmds:
- go build -o app main.go
run:
cmds:
- ./app
66 changes: 66 additions & 0 deletions examples/psutil/mem/vmem/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package main

import (
"log"
"time"

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

func main() {
log.SetFlags(log.Ltime)

if err := run(); err != nil {
log.Fatal(err)
}
}

func run() error {
const (
COUNT = 5
)
var (
interval = 1 * time.Second
mb = func(v uint64) uint64 {
// 概算値で良いので整数除算
return v >> 20
}
done = make(chan struct{})
useMem = func(done <-chan struct{}, ready chan<- struct{}, bufSize uint64) {
buf := make([]byte, bufSize)
for i := range len(buf) {
buf[i] = 0
}

close(ready)
<-done
}
)
for range COUNT {
// 現在のメモリ量を取得
var (
vms *mem.VirtualMemoryStat
err error
)
vms, err = mem.VirtualMemory()
if err != nil {
return err
}

log.Printf("Total=%4dMB\tUsed=%4dMB\tFree=%4dMB", mb(vms.Total), mb(vms.Used), mb(vms.Free))

// 意図的にメモリを占有していく
var (
ready = make(chan struct{})
)
go useMem(done, ready, 150<<20)
<-ready

time.Sleep(interval)
}

close(done)
time.Sleep(500 * time.Millisecond)

return nil
}
Loading