Skip to content

Instantly share code, notes, and snippets.

@candera
Created July 7, 2014 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save candera/8ad5ddc860755aff0098 to your computer and use it in GitHub Desktop.
Save candera/8ad5ddc860755aff0098 to your computer and use it in GitHub Desktop.
Measure CPU utilization
(defn- cpu-stats
"Returns measures of the various types of CPU usage to date"
[]
(->> (-> (clojure.java.shell/sh "cat" "/proc/stat")
:out
(clojure.string/split #"\n")
first
(clojure.string/split #"\s"))
(remove clojure.string/blank?)
(drop 1)
(map #(Integer/parseInt %))))
(defn start-cpu-meter
"Create and return a new CPU meter, an opaque data structure meant
only to be passed to `sample-cpu-meter`."
[]
(cpu-stats))
(defn sample-cpu-meter
"Returns a floating point number between 0 and 1 representing CPU
utilization between the time `meter` was started and the call to
this function."
[meter]
(let [end-stats (cpu-stats)
[a b c idle & more] (map - end-stats meter)]
(- 1.0 (/ idle (apply + a b c idle more)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment