Skip to content

Instantly share code, notes, and snippets.

@ponkotuy
Created September 13, 2019 11:50
Show Gist options
  • Save ponkotuy/004e83d4d2bacaedc767a3d54997c24f to your computer and use it in GitHub Desktop.
Save ponkotuy/004e83d4d2bacaedc767a3d54997c24f to your computer and use it in GitHub Desktop.
Scalaで/proc/statのCPU情報を解析するだけの簡単な
package utils
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}
import scala.collection.JavaConverters._
object ProcStat {
val StatPath = Paths.get("/proc/stat")
def cpuStats: CpuStats = {
val lines = Files.readAllLines(StatPath, StandardCharsets.US_ASCII).asScala
val all = CpuStat.fromLine(lines.head)
val cores = lines.tail.flatMap { line =>
if(line.startsWith("cpu")) {
Some(CpuStat.fromLine(line))
} else None
}
CpuStats(all, cores)
}
}
case class CpuStats(all: CpuStat, cores: Seq[CpuStat])
case class CpuStat(user: Long, nice: Long, system: Long, idle: Long) {
def usage: Double = (user + nice + system) / (user + nice + system + idle)
}
object CpuStat {
val Spaces = """\s+""".r
def fromLine(line: String) = {
val Array(_, user, nice, system, idle) = Spaces.split(line).take(5)
CpuStat(user.toLong, nice.toLong, system.toLong, idle.toLong)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment