Skip to content

Instantly share code, notes, and snippets.

@moson-mo
Created March 12, 2023 15:14
Show Gist options
  • Save moson-mo/89e1d465fefc754d72eadece96443b4b to your computer and use it in GitHub Desktop.
Save moson-mo/89e1d465fefc754d72eadece96443b4b to your computer and use it in GitHub Desktop.
Expose CPU power consumption (AMD ZenX processors) via REST-API
package main
import (
"encoding/binary"
"fmt"
"net/http"
"os"
"sync"
"time"
)
var (
pwr = 0.0
mut = sync.RWMutex{}
)
const (
pwrMultiplier = 1.52588e-05
)
func main() {
f, _ := os.OpenFile("/dev/cpu/0/msr", os.O_RDONLY, os.ModeDevice)
defer f.Close()
f.Seek(0xC001029B, 0)
go read(f)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
mut.RLock()
fmt.Fprintf(w, "%.2f", pwr)
mut.RUnlock()
})
http.ListenAndServe(":9998", nil)
}
func read(f *os.File) float64 {
var rawa uint64
var rawb uint64
for {
binary.Read(f, binary.LittleEndian, &rawa)
time.Sleep(1000 * time.Millisecond)
binary.Read(f, binary.LittleEndian, &rawb)
mut.Lock()
pwr = float64(rawb-rawa) * pwrMultiplier
mut.Unlock()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment