Introduce a benchmark to compare the architecture-optimized strchr()
implementation against the generic C version (__generic_strchr).

Suggested-by: Andy Shevchenko <[email protected]>
Signed-off-by: Feng Jiang <[email protected]>
---
 lib/tests/string_kunit.c | 49 +++++++++++++++++++++++++++++++++++++++-
 1 file changed, 48 insertions(+), 1 deletion(-)

diff --git a/lib/tests/string_kunit.c b/lib/tests/string_kunit.c
index 6578b36213bc..e8d527336030 100644
--- a/lib/tests/string_kunit.c
+++ b/lib/tests/string_kunit.c
@@ -20,7 +20,8 @@
 #define STRING_TEST_MAX_LEN    128
 #define STRING_TEST_MAX_OFFSET 16
 
-#if defined(__HAVE_ARCH_STRLEN) || defined(__HAVE_ARCH_STRNLEN)
+#if defined(__HAVE_ARCH_STRLEN) || defined(__HAVE_ARCH_STRNLEN) || \
+       defined(__HAVE_ARCH_STRCHR)
 #define STRING_BENCH_ENABLED
 #endif
 
@@ -367,6 +368,49 @@ static void string_test_strrchr(struct kunit *test)
        }
 }
 
+#ifdef __HAVE_ARCH_STRCHR
+static void string_test_strchr_bench(struct kunit *test)
+{
+       char *buf;
+       size_t buf_len, iters;
+       ktime_t start, end;
+       u64 time_arch, time_generic;
+
+       buf_len = get_max_bench_len(bench_cases, ARRAY_SIZE(bench_cases)) + 1;
+
+       buf = kunit_kzalloc(test, buf_len, GFP_KERNEL);
+       KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buf);
+
+       for (size_t i = 0; i < ARRAY_SIZE(bench_cases); i++) {
+               get_random_nonzero_bytes(buf, bench_cases[i].len);
+               buf[bench_cases[i].len] = '\0';
+
+               iters = bench_cases[i].iterations;
+
+               /* 1. Benchmark the architecture-optimized version */
+               start = ktime_get();
+               for (unsigned int j = 0; j < iters; j++) {
+                       OPTIMIZER_HIDE_VAR(buf);
+                       (void)strchr(buf, '\0');
+               }
+               end = ktime_get();
+               time_arch = ktime_to_ns(ktime_sub(end, start));
+
+               /* 2. Benchmark the generic C version */
+               start = ktime_get();
+               for (unsigned int j = 0; j < iters; j++) {
+                       OPTIMIZER_HIDE_VAR(buf);
+                       (void)__generic_strchr(buf, '\0');
+               }
+               end = ktime_get();
+               time_generic = ktime_to_ns(ktime_sub(end, start));
+
+               string_bench_report(test, "strchr", &bench_cases[i],
+                               time_arch, time_generic);
+       }
+}
+#endif
+
 static void string_test_strnchr(struct kunit *test)
 {
        const char *test_string = "abcdefghijkl";
@@ -867,6 +911,9 @@ static struct kunit_case string_test_cases[] = {
        KUNIT_CASE(string_test_strnlen_bench),
 #endif
        KUNIT_CASE(string_test_strchr),
+#ifdef __HAVE_ARCH_STRCHR
+       KUNIT_CASE(string_test_strchr_bench),
+#endif
        KUNIT_CASE(string_test_strnchr),
        KUNIT_CASE(string_test_strrchr),
        KUNIT_CASE(string_test_strspn),
-- 
2.25.1


Reply via email to