Skip to content

Commit f47a229

Browse files
committed
selftests/bpf: add usage example for cpu time counter kfuncs
The selftest provides an example of how to measure the latency of bpf kfunc/helper call using time stamp counter and how to convert measured value into nanoseconds. Signed-off-by: Vadim Fedorenko <[email protected]>
1 parent 220cd7d commit f47a229

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
/* Copyright (c) 2024 Meta Inc. */
3+
4+
#include <test_progs.h>
5+
#include "test_cpu_cycles.skel.h"
6+
7+
static void cpu_cycles(void)
8+
{
9+
LIBBPF_OPTS(bpf_test_run_opts, opts);
10+
struct test_cpu_cycles *skel;
11+
int err, pfd;
12+
13+
skel = test_cpu_cycles__open_and_load();
14+
if (!ASSERT_OK_PTR(skel, "test_cpu_cycles open and load"))
15+
return;
16+
17+
pfd = bpf_program__fd(skel->progs.bpf_cpu_cycles);
18+
if (!ASSERT_GT(pfd, 0, "test_cpu_cycles fd"))
19+
goto fail;
20+
21+
err = bpf_prog_test_run_opts(pfd, &opts);
22+
if (!ASSERT_OK(err, "test_cpu_cycles test run"))
23+
goto fail;
24+
25+
ASSERT_NEQ(skel->bss->cycles, 0, "test_cpu_cycles 0 cycles");
26+
ASSERT_NEQ(skel->bss->ns, 0, "test_cpu_cycles 0 ns");
27+
fail:
28+
test_cpu_cycles__destroy(skel);
29+
}
30+
31+
void test_cpu_cycles(void)
32+
{
33+
if (test__start_subtest("cpu_cycles"))
34+
cpu_cycles();
35+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
/* Copyright (c) 2024 Meta Inc. */
3+
4+
#include "vmlinux.h"
5+
#include <bpf/bpf_helpers.h>
6+
7+
extern u64 bpf_cpu_time_counter_to_ns(u64 cycles) __weak __ksym;
8+
extern u64 bpf_get_cpu_time_counter(void) __weak __ksym;
9+
10+
__u64 cycles, ns;
11+
12+
SEC("syscall")
13+
int bpf_cpu_cycles(void)
14+
{
15+
struct bpf_pidns_info pidns;
16+
__u64 start;
17+
18+
start = bpf_get_cpu_time_counter();
19+
bpf_get_ns_current_pid_tgid(0, 0, &pidns, sizeof(struct bpf_pidns_info));
20+
cycles = bpf_get_cpu_time_counter() - start;
21+
ns = bpf_cpu_time_counter_to_ns(cycles);
22+
return 0;
23+
}
24+
25+
char _license[] SEC("license") = "GPL";

0 commit comments

Comments
 (0)