From 7226cb86747d5ed44a894284781f2dd22a14d8d6 Mon Sep 17 00:00:00 2001 From: Maximilian Linhoff Date: Thu, 4 Jan 2024 14:04:06 +0100 Subject: [PATCH 1/2] Use a much shorter time to measure current cpu frequency --- cpuinfo/cpuinfo.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/cpuinfo/cpuinfo.py b/cpuinfo/cpuinfo.py index 291080e..b0b17e7 100644 --- a/cpuinfo/cpuinfo.py +++ b/cpuinfo/cpuinfo.py @@ -31,6 +31,7 @@ import platform import multiprocessing import ctypes +from time import perf_counter CAN_CALL_CPUID_IN_SUBPROCESS = True @@ -1517,19 +1518,22 @@ def new_func(): retval = get_ticks_x86_64 return retval - def get_raw_hz(self): - from time import sleep + def get_raw_hz(self, measurement_time=0.01): + from time import sleep, perf_counter ticks_fn = self.get_ticks_func() + t0 = perf_counter() start = ticks_fn.func() - sleep(1) + sleep(measurement_time) end = ticks_fn.func() + t1 = perf_counter() + measurement_time = (t1 - t0) - ticks = (end - start) + frequency = (end - start) / measurement_time ticks_fn.free() - return ticks + return frequency def _get_cpu_info_from_cpuid_actual(): ''' From 710c80d781f567580e8aa0689a042ec85e99fa7a Mon Sep 17 00:00:00 2001 From: Maximilian Linhoff Date: Thu, 4 Jan 2024 14:28:37 +0100 Subject: [PATCH 2/2] Add comment, account for time spend in ticks_fun --- cpuinfo/cpuinfo.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/cpuinfo/cpuinfo.py b/cpuinfo/cpuinfo.py index b0b17e7..e51cc24 100644 --- a/cpuinfo/cpuinfo.py +++ b/cpuinfo/cpuinfo.py @@ -1519,18 +1519,27 @@ def new_func(): return retval def get_raw_hz(self, measurement_time=0.01): - from time import sleep, perf_counter + from time import sleep, perf_counter_ns ticks_fn = self.get_ticks_func() - t0 = perf_counter() + # when testing, more consistent results between different + # measurement times were obtained by measuring the actual time + # spend, not just using the user-provided value. For some reason, + # it was also better to have the time around the ticks_func / sleep calls + # and then account for the time spend in the ticks_func + ticks_start = perf_counter_ns() + ticks_fn.func() + ticks_fn_time = perf_counter_ns() - ticks_start + + t0 = perf_counter_ns() start = ticks_fn.func() sleep(measurement_time) end = ticks_fn.func() - t1 = perf_counter() - measurement_time = (t1 - t0) + t1 = perf_counter_ns() + measurement_time = (t1 - t0) - 2 * ticks_fn_time - frequency = (end - start) / measurement_time + frequency = 1e9 * (end - start) / measurement_time ticks_fn.free() return frequency