git.cappig.dev / apheleiaOS.git master

1
#include <errno.h>
2
#include <stdbool.h>
3
#include <sys/proc.h>
4
#include <sys/times.h>
5
#include <time.h>
6
7
#define TIMES_HZ 100
8
9
clock_t times(struct tms *buf) {
10
    if (buf) {
11
        proc_stat_t stat = { 0 };
12
        if (proc_stat_read_path("/proc/self/stat", &stat) >= 0) {
13
            clock_t user_ticks = (clock_t)((stat.user_time_ms * TIMES_HZ) / 1000ULL);
14
            clock_t sys_ticks = (clock_t)((stat.sys_time_ms * TIMES_HZ) / 1000ULL);
15
            clock_t child_user_ticks = (clock_t)((stat.child_user_time_ms * TIMES_HZ) / 1000ULL);
16
            clock_t child_sys_ticks = (clock_t)((stat.child_sys_time_ms * TIMES_HZ) / 1000ULL);
17
18
            buf->tms_utime = user_ticks;
19
            buf->tms_stime = sys_ticks;
20
            buf->tms_cutime = child_user_ticks;
21
            buf->tms_cstime = child_sys_ticks;
22
        } else {
23
            buf->tms_utime = 0;
24
            buf->tms_stime = 0;
25
            buf->tms_cutime = 0;
26
            buf->tms_cstime = 0;
27
        }
28
    }
29
30
    struct timespec now = { 0 };
31
    if (clock_gettime(CLOCK_MONOTONIC, &now) < 0) {
32
        return (clock_t)-1;
33
    }
34
35
    return (clock_t)(now.tv_sec * TIMES_HZ) + (clock_t)((now.tv_nsec * TIMES_HZ) / 1000000000L);
36
}