Created
September 13, 2019 11:50
-
-
Save ponkotuy/004e83d4d2bacaedc767a3d54997c24f to your computer and use it in GitHub Desktop.
Scalaで/proc/statのCPU情報を解析するだけの簡単な
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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