Re: [patch 18/38] lib/tests: Replace get_cycles() with ktime_get()

Geert Uytterhoeven
2026-04-16T10:31:18Z

Hi Thomas,

On Fri, 10 Apr 2026 at 14:20, Thomas Gleixner <tglx@kernel.org> wrote:
> get_cycles() is the historical access to a fine grained time source, but it
> is a suboptimal choice for two reasons:
>
> - get_cycles() is not guaranteed to be supported and functional on all
> systems/platforms. If not supported or not functional it returns 0,
> which makes benchmarking moot.
>
> - get_cycles() returns the raw counter value of whatever the
> architecture platform provides. The original x86 Time Stamp Counter
> (TSC) was despite its name tied to the actual CPU core frequency.
> That's not longer the case. So the counter value is only meaningful
> when the CPU operates at the same frequency as the TSC or the value is
> adjusted to the actual CPU frequency. Other architectures and
> platforms provide similar disjunct counters via get_cycles(), so the
> result is operations per BOGO-cycles, which is not really meaningful.
>
> Use ktime_get() instead which provides nanosecond timestamps with the
> granularity of the underlying hardware counter, which is not different to
> the variety of get_cycles() implementations.
>
> This provides at least understandable metrics, i.e. operations/nanoseconds,
> and is available on all platforms. As with get_cycles() the result might
> have to be put into relation with the CPU operating frequency, but that's
> not any different.
>
> This is part of a larger effort to remove get_cycles() usage from
> non-architecture code.
>
> Signed-off-by: Thomas Gleixner <tglx@kernel.org>

Thanks for your patch!

> --- a/lib/interval_tree_test.c
> +++ b/lib/interval_tree_test.c
> @@ -65,13 +65,13 @@ static void init(void)
> static int basic_check(void)
> {
> int i, j;
> - cycles_t time1, time2, time;
> + ktime_t time1, time2, time;
>
> printk(KERN_ALERT "interval tree insert/remove");
>
> init();
>
> - time1 = get_cycles();
> + time1 = ktime_get();
>
> for (i = 0; i < perf_loops; i++) {
> for (j = 0; j < nnodes; j++)
> @@ -80,11 +80,11 @@ static int basic_check(void)
> interval_tree_remove(nodes + j, &root);
> }
>
> - time2 = get_cycles();
> + time2 = ktime_get();
> time = time2 - time1;
>
> time = div_u64(time, perf_loops);
> - printk(" -> %llu cycles\n", (unsigned long long)time);
> + printk(" -> %llu nsecs\n", (unsigned long long)time);

While cycles_t was unsigned long or long long, ktime_t is always s64,
so "%lld", and the cast can be dropped (everywhere).

Gr{oetje,eeting}s,

Geert

--
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- geert@linux-m68k.org

In personal conversations with technical people, I call myself a hacker. But
when I'm talking to journalists I just say "programmer" or something like that.
-- Linus Torvalds