xref: /dpdk/app/test/test_rand_perf.c (revision 089e5ed727a15da2729cfee9b63533dd120bd04c)
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2019 Ericsson AB
3  */
4 
5 #include <inttypes.h>
6 #include <stdio.h>
7 
8 #include <rte_common.h>
9 #include <rte_cycles.h>
10 #include <rte_random.h>
11 
12 #include "test.h"
13 
14 static volatile uint64_t vsum;
15 
16 #define ITERATIONS (100000000)
17 
18 #define BEST_CASE_BOUND (1<<16)
19 #define WORST_CASE_BOUND (BEST_CASE_BOUND + 1)
20 
21 enum rand_type {
22 	rand_type_64,
23 	rand_type_bounded_best_case,
24 	rand_type_bounded_worst_case
25 };
26 
27 static const char *
28 rand_type_desc(enum rand_type rand_type)
29 {
30 	switch (rand_type) {
31 	case rand_type_64:
32 		return "Full 64-bit [rte_rand()]";
33 	case rand_type_bounded_best_case:
34 		return "Bounded average best-case [rte_rand_max()]";
35 	case rand_type_bounded_worst_case:
36 		return "Bounded average worst-case [rte_rand_max()]";
37 	default:
38 		return NULL;
39 	}
40 }
41 
42 static __rte_always_inline void
43 test_rand_perf_type(enum rand_type rand_type)
44 {
45 	uint64_t start;
46 	uint32_t i;
47 	uint64_t end;
48 	uint64_t sum = 0;
49 	uint64_t op_latency;
50 
51 	start = rte_rdtsc();
52 
53 	for (i = 0; i < ITERATIONS; i++) {
54 		switch (rand_type) {
55 		case rand_type_64:
56 			sum += rte_rand();
57 			break;
58 		case rand_type_bounded_best_case:
59 			sum += rte_rand_max(BEST_CASE_BOUND);
60 			break;
61 		case rand_type_bounded_worst_case:
62 			sum += rte_rand_max(WORST_CASE_BOUND);
63 			break;
64 		}
65 	}
66 
67 	end = rte_rdtsc();
68 
69 	/* to avoid an optimizing compiler removing the whole loop */
70 	vsum = sum;
71 
72 	op_latency = (end - start) / ITERATIONS;
73 
74 	printf("%s: %"PRId64" TSC cycles/op\n", rand_type_desc(rand_type),
75 	       op_latency);
76 }
77 
78 static int
79 test_rand_perf(void)
80 {
81 	rte_srand(42);
82 
83 	printf("Pseudo-random number generation latencies:\n");
84 
85 	test_rand_perf_type(rand_type_64);
86 	test_rand_perf_type(rand_type_bounded_best_case);
87 	test_rand_perf_type(rand_type_bounded_worst_case);
88 
89 	return 0;
90 }
91 
92 REGISTER_TEST_COMMAND(rand_perf_autotest, test_rand_perf);
93