PageRenderTime 10ms CodeModel.GetById 1ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/mode-line/modeline-cpu.lisp

http://github.com/joelagnel/stumpwm-goodies
Lisp | 48 lines | 42 code | 3 blank | 3 comment | 2 complexity | 2a7e67872eb4f6f3200d522743583633 MD5 | raw file
 1(defvar *prev-user-cpu* 0)
 2(defvar *prev-sys-cpu* 0)
 3(defvar *prev-idle-cpu* 0)
 4(defvar *prev-iowait* 0)
 5
 6(defun current-cpu-usage ()
 7  "Return the average CPU usage since the last call.
 8       First value is percent of CPU in use.
 9       Second value is percent of CPU in use by system processes.
10       Third value is percent of time since last call spent waiting for IO (or 0 if not available)."
11  (let ((cpu-result 0)
12        (sys-result 0)
13        (io-result nil))
14    (with-open-file (in "/proc/stat" :direction :input)
15      (if (eq 'cpu (read in))
16          (let* ((norm-user (read in))
17                 (nice-user (read in))
18                 (user (+ norm-user nice-user))
19                 (sys (read in))
20                 (idle (read in))
21                 (iowait (or (ignore-errors (read in)) 0))
22                 (step-denom (- (+ user sys idle iowait)
23                                (+ *prev-user-cpu* *prev-sys-cpu* *prev-idle-cpu* *prev-iowait*))))
24            (setf cpu-result (/ (- (+ user sys)
25                                   (+ *prev-user-cpu* *prev-sys-cpu*))
26                                step-denom)
27                  sys-result (/ (- sys *prev-sys-cpu*)
28                                step-denom)
29                  io-result (/ (- iowait *prev-iowait*)
30                               step-denom)
31                  *prev-user-cpu* user
32                  *prev-sys-cpu* sys
33                  *prev-idle-cpu* idle
34                  *prev-iowait* iowait))
35          (warn "Unexpected header")))
36    (values cpu-result sys-result io-result)))
37
38(defun format-current-cpu-usage (stream)
39  "Formats a string representing the current processor usage to STREAM.
40       Arguments are as those to FORMAT, so NIL returns a formatted string and T prints to standard
41       output."
42  (multiple-value-bind (cpu sys io) (current-cpu-usage)
43    (declare (ignore sys))
44    (format stream "[cpu:~3D%] [io:~3D%]" (truncate (* 100 cpu)) (if io (truncate (* 100 io)) 0))))
45
46;;     (setf *screen-mode-line-format* (list "%w   "
47;;                                           ;; ... some other modeline settings ...
48;;                                           '(:eval (format-current-cpu-usage nil))))