Skip to content

Commit

Permalink
- first
Browse files Browse the repository at this point in the history
  • Loading branch information
chrispassas committed Jun 30, 2022
0 parents commit b6a543c
Show file tree
Hide file tree
Showing 4 changed files with 139 additions and 0 deletions.
28 changes: 28 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package main

import (
"log"
"os"
"time"

"github.com/chrispassas/peak"
)

func main() {
log.Printf("start")
log.Printf("pid:%d", os.Getpid())

// os.Stderr.Close()
os.Stdout.Close()
// os.Stdin.Close()

for x := 0; x < 10; x++ {
log.Printf("x:%d", x)
time.Sleep(time.Second * 2)
log.Printf("peak mem:%d", peak.PeakMemory())
log.Printf("peak goroutines:%d", peak.PeakGoRoutines())
log.Printf("peak fd:%d", peak.PeakFileHandles())
}

log.Printf("end")
}
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/chrispassas/peak

go 1.18
108 changes: 108 additions & 0 deletions peak.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package peak

import (
"log"
"os"
"runtime"
"sync"
"time"
)

var m2 sync.RWMutex
var interval = time.Second * 2

var m sync.RWMutex
var peakMemory uint64
var peakGoRoutines uint64
var peakFileDescriptors uint64

func init() {
go update()
}

func update() {
for {
updatePeakMemory()
updatePeakGoroutines()
updateFileDescriptors()
m2.RLock()
time.Sleep(interval)
m2.RUnlock()
}
}

func updatePeakMemory() {
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
m.Lock()
defer m.Unlock()
if mem.Alloc > peakMemory {
peakMemory = mem.Alloc
}
}

func updatePeakGoroutines() {
count := uint64(runtime.NumGoroutine())
m.Lock()
defer m.Unlock()
if count > peakGoRoutines {
peakGoRoutines = count
}
}

func updateFileDescriptors() {
var fdPath string
switch runtime.GOOS {
case "darwin":
fdPath = "/dev/fd"
case "linux", "freebsd":
fdPath = "/proc/self/fd"
default:
return
}

entries, err := os.ReadDir(fdPath)
log.Printf("fd count:%d error:%v", entries, err)
for _, e := range entries {
log.Printf("[DEBUG] name:%s type:%s", e.Name(), e.Type())
}
// files, _ := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", pid))

m.Lock()
defer m.Unlock()
peakFileDescriptors = uint64(len(entries))
}

func PeakMemory() uint64 {
m.RLock()
defer m.RUnlock()
return peakMemory
}

func PeakGoRoutines() uint64 {
m.RLock()
defer m.RUnlock()
return peakGoRoutines
}

func PeakFileHandles() uint64 {
m.RLock()
defer m.RUnlock()
return peakFileDescriptors
}

func Reset() {
m.Lock()
defer m.Unlock()
peakMemory = 0
peakGoRoutines = 0
peakFileDescriptors = 0
}

func SetInterval(dur time.Duration) {
if dur > 0 {
m2.Lock()
interval = dur
m2.Unlock()
}
}
Empty file added readme.md
Empty file.

0 comments on commit b6a543c

Please sign in to comment.