Skip to content

Instantly share code, notes, and snippets.

@mmennis
Created August 28, 2012 16:24
Show Gist options
  • Save mmennis/3499915 to your computer and use it in GitHub Desktop.
Save mmennis/3499915 to your computer and use it in GitHub Desktop.
Yammer metrics CPU guage
import com.yammer.metrics.Metrics
import com.yammer.metrics.core.{Gauge, MetricName}
import management.{RuntimeMXBean, ManagementFactory}
import com.sun.management.UnixOperatingSystemMXBean
class PercentCpuGauge extends Gauge[Double] {
val runBean: RuntimeMXBean = ManagementFactory.getRuntimeMXBean
val osBean: UnixOperatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean.asInstanceOf[UnixOperatingSystemMXBean]
var lastUptime: Long = runBean.getUptime
var lastCpuTime: Long = osBean.getProcessCpuTime
def value() = {
var retVal: Double = 0.00
var upTime = runBean.getUptime
var elapsedTime = upTime - lastUptime
if ( elapsedTime > 0 ) {
var cpuTime = osBean.getProcessCpuTime
// Uptime in milliseconds but cpu time in nanoseconds
// correction should be 10^6 but multiply but multiply by 100 for percentage
retVal = (cpuTime - lastCpuTime)/(elapsedTime.toDouble * 10000)
lastUptime = upTime
lastCpuTime = cpuTime
}
retVal
}
}
val cpuGauge = new PercentCpuGauge()
val newCpuGuage = Metrics.newGauge(new MetricName(cpuGauge.getClass, "cpu_percentage"), cpuGauge)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment