Chris Wilson | b98bade | 2013-08-20 21:39:27 +0100 | [diff] [blame] | 1 | /* |
| 2 | * Copyright © 2013 Intel Corporation |
| 3 | * |
| 4 | * Permission is hereby granted, free of charge, to any person obtaining a |
| 5 | * copy of this software and associated documentation files (the "Software"), |
| 6 | * to deal in the Software without restriction, including without limitation |
| 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, |
| 8 | * and/or sell copies of the Software, and to permit persons to whom the |
| 9 | * Software is furnished to do so, subject to the following conditions: |
| 10 | * |
| 11 | * The above copyright notice and this permission notice (including the next |
| 12 | * paragraph) shall be included in all copies or substantial portions of the |
| 13 | * Software. |
| 14 | * |
| 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL |
| 18 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| 20 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS |
| 21 | * IN THE SOFTWARE. |
| 22 | * |
| 23 | */ |
| 24 | |
Chris Wilson | 6a64ee9 | 2013-08-18 15:56:22 +0100 | [diff] [blame] | 25 | #include <stdio.h> |
| 26 | #include <unistd.h> |
| 27 | #include <fcntl.h> |
| 28 | #include <errno.h> |
| 29 | |
| 30 | #include "cpu-top.h" |
| 31 | |
| 32 | int cpu_top_update(struct cpu_top *cpu) |
| 33 | { |
| 34 | struct cpu_stat *s = &cpu->stat[cpu->count++&1]; |
| 35 | struct cpu_stat *d = &cpu->stat[cpu->count&1]; |
| 36 | uint64_t d_total, d_idle; |
| 37 | char buf[4096]; |
| 38 | int fd, len = -1; |
| 39 | |
| 40 | fd = open("/proc/stat", 0); |
| 41 | if (fd < 0) |
| 42 | return errno; |
| 43 | |
| 44 | len = read(fd, buf, sizeof(buf)-1); |
| 45 | close(fd); |
| 46 | |
| 47 | if (len < 0) |
| 48 | return EIO; |
| 49 | buf[len] = '\0'; |
| 50 | |
| 51 | #ifdef __x86_64__ |
| 52 | sscanf(buf, "cpu %lu %lu %lu %lu", |
| 53 | &s->user, &s->nice, &s->sys, &s->idle); |
| 54 | #else |
| 55 | sscanf(buf, "cpu %llu %llu %llu %llu", |
| 56 | &s->user, &s->nice, &s->sys, &s->idle); |
| 57 | #endif |
| 58 | |
| 59 | s->total = s->user + s->nice + s->sys + s->idle; |
| 60 | if (cpu->count == 1) |
| 61 | return EAGAIN; |
| 62 | |
| 63 | d_total = s->total - d->total; |
| 64 | d_idle = s->idle - d->idle; |
| 65 | cpu->busy = 100 - 100 * d_idle / d_total; |
| 66 | |
| 67 | return 0; |
| 68 | } |