time-util: use sysconf_clock_ticks_cached() at all places we query _SC_CLK_TCK

This commit is contained in:
Lennart Poettering
2026-07-01 16:14:19 +02:00
parent 60bac209eb
commit 818b3b31e6
3 changed files with 14 additions and 17 deletions
+3 -7
View File
@@ -131,7 +131,6 @@ int procfs_cpu_get_usage(nsec_t *ret) {
_cleanup_free_ char *first_line = NULL;
unsigned long user_ticks, nice_ticks, system_ticks, irq_ticks, softirq_ticks,
guest_ticks = 0, guest_nice_ticks = 0;
long ticks_per_second;
uint64_t sum, gcd, a, b;
const char *p;
int r;
@@ -156,10 +155,7 @@ int procfs_cpu_get_usage(nsec_t *ret) {
&guest_nice_ticks) < 5) /* we only insist on the first five fields */
return -EINVAL;
ticks_per_second = sysconf(_SC_CLK_TCK);
if (ticks_per_second < 0)
return -errno;
assert(ticks_per_second > 0);
uint64_t ticks_per_second = sysconf_clock_ticks_cached();
sum = (uint64_t) user_ticks + (uint64_t) nice_ticks + (uint64_t) system_ticks +
(uint64_t) irq_ticks + (uint64_t) softirq_ticks +
@@ -168,8 +164,8 @@ int procfs_cpu_get_usage(nsec_t *ret) {
/* Let's reduce this fraction before we apply it to avoid overflows when converting this to μsec */
gcd = calc_gcd64(NSEC_PER_SEC, ticks_per_second);
a = (uint64_t) NSEC_PER_SEC / gcd;
b = (uint64_t) ticks_per_second / gcd;
a = NSEC_PER_SEC / gcd;
b = ticks_per_second / gcd;
*ret = DIV_ROUND_UP((nsec_t) sum * (nsec_t) a, (nsec_t) b);
return 0;
+9 -10
View File
@@ -1766,27 +1766,26 @@ int localtime_or_gmtime_usec(
return 0;
}
static uint32_t sysconf_clock_ticks_cached(void) {
static thread_local uint32_t hz = 0;
long r;
uint64_t sysconf_clock_ticks_cached(void) {
static thread_local uint64_t hz = 0;
if (hz == 0) {
r = sysconf(_SC_CLK_TCK);
if (hz != 0)
return hz;
assert(r > 0);
hz = r;
}
long t = sysconf(_SC_CLK_TCK);
assert(t > 0);
hz = (uint64_t) t;
return hz;
}
uint32_t usec_to_jiffies(usec_t u) {
uint32_t hz = sysconf_clock_ticks_cached();
uint64_t hz = sysconf_clock_ticks_cached();
return DIV_ROUND_UP(u, USEC_PER_SEC / hz);
}
usec_t jiffies_to_usec(uint32_t j) {
uint32_t hz = sysconf_clock_ticks_cached();
uint64_t hz = sysconf_clock_ticks_cached();
return DIV_ROUND_UP(j * USEC_PER_SEC, hz);
}
+2
View File
@@ -201,6 +201,8 @@ static inline int parse_birth_date(const char *s, struct tm *ret) {
return parse_calendar_date_full(s, /* allow_pre_epoch= */ true, NULL, ret);
}
uint64_t sysconf_clock_ticks_cached(void);
uint32_t usec_to_jiffies(usec_t usec);
usec_t jiffies_to_usec(uint32_t jiffies);