Debian Codegraph @

third-party/xxhash/cli/xsum_bench.c

raw
1 /*
2 * xsum_bench - Benchmark functions for xxhsum
3 * Copyright (C) 2013-2021 Yann Collet
4 *
5 * GPL v2 License
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * You can contact the author at:
22 * - xxHash homepage: https://www.xxhash.com
23 * - xxHash source repository: https://github.com/Cyan4973/xxHash
24 */
25
26 #include "xsum_output.h" /* XSUM_logLevel */
27 #include "xsum_bench.h"
28 #include "xsum_sanity_check.h" /* XSUM_fillTestBuffer */
29 #include "xsum_os_specific.h" /* XSUM_getFileSize */
30 #ifndef XXH_STATIC_LINKING_ONLY
31 # define XXH_STATIC_LINKING_ONLY
32 #endif
33 #include "../xxhash.h"
34 #ifdef XXHSUM_DISPATCH
35 # include "../xxh_x86dispatch.h" /* activate _dispatch() redirectors */
36 #endif
37
38 #include <stdlib.h> /* malloc, free */
39 #include <assert.h>
40 #include <string.h> /* strlen, memcpy */
41 #include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */
42 #include <errno.h> /* errno */
43
44 #define TIMELOOP_S 1
45 #define TIMELOOP (TIMELOOP_S * CLOCKS_PER_SEC) /* target timing per iteration */
46 #define TIMELOOP_MIN (TIMELOOP / 2) /* minimum timing to validate a result */
47
48 /* Each benchmark iteration attempts to match TIMELOOP (1 second).
49 * The nb of loops is adjusted at each iteration to reach that target.
50 * However, initially, there is no information, so 1st iteration blindly targets an arbitrary speed.
51 * If it's too small, it will be adjusted, and a new attempt will be made.
52 * But if it's too large, the first iteration can be very long,
53 * before being fixed at second attempt.
54 * So prefer starting with small speed targets.
55 * XXH_1ST_SPEED_TARGET is defined in MB/s */
56 #ifndef XXH_1ST_SPEED_TARGET
57 # define XXH_1ST_SPEED_TARGET 10
58 #endif
59
60 #define MAX_MEM (2 GB - 64 MB)
61
62 static clock_t XSUM_clockSpan( clock_t start )
63 {
64 return clock() - start; /* works even if overflow; Typical max span ~ 30 mn */
65 }
66
67 static size_t XSUM_findMaxMem(XSUM_U64 requiredMem)
68 {
69 size_t const step = 64 MB;
70 void* testmem = NULL;
71
72 requiredMem = (((requiredMem >> 26) + 1) << 26);
73 requiredMem += 2*step;
74 if (requiredMem > MAX_MEM) requiredMem = MAX_MEM;
75
76 while (!testmem) {
77 if (requiredMem > step) requiredMem -= step;
78 else requiredMem >>= 1;
79 testmem = malloc ((size_t)requiredMem);
80 }
81 free (testmem);
82
83 /* keep some space available */
84 if (requiredMem > step) requiredMem -= step;
85 else requiredMem >>= 1;
86
87 return (size_t)requiredMem;
88 }
89
90 /*
91 * A secret buffer used for benchmarking XXH3's withSecret variants.
92 *
93 * In order for the bench to be realistic, the secret buffer would need to be
94 * pre-generated.
95 *
96 * Adding a pointer to the parameter list would be messy.
97 */
98 static XSUM_U8 g_benchSecretBuf[XXH3_SECRET_SIZE_MIN];
99
100 /*
101 * Wrappers for the benchmark.
102 *
103 * If you would like to add other hashes to the bench, create a wrapper and add
104 * it to the g_hashesToBench table. It will automatically be added.
105 */
106 typedef XSUM_U32 (*hashFunction)(const void* buffer, size_t bufferSize, XSUM_U32 seed);
107
108 static XSUM_U32 localXXH32(const void* buffer, size_t bufferSize, XSUM_U32 seed)
109 {
110 return XXH32(buffer, bufferSize, seed);
111 }
112 static XSUM_U32 localXXH32_stream(const void* buffer, size_t bufferSize, XSUM_U32 seed)
113 {
114 XXH32_state_t state;
115 (void)seed;
116 XXH32_reset(&state, seed);
117 XXH32_update(&state, buffer, bufferSize);
118 return (XSUM_U32)XXH32_digest(&state);
119 }
120 static XSUM_U32 localXXH64(const void* buffer, size_t bufferSize, XSUM_U32 seed)
121 {
122 return (XSUM_U32)XXH64(buffer, bufferSize, seed);
123 }
124 static XSUM_U32 localXXH64_stream(const void* buffer, size_t bufferSize, XSUM_U32 seed)
125 {
126 XXH64_state_t state;
127 (void)seed;
128 XXH64_reset(&state, seed);
129 XXH64_update(&state, buffer, bufferSize);
130 return (XSUM_U32)XXH64_digest(&state);
131 }
132 static XSUM_U32 localXXH3_64b(const void* buffer, size_t bufferSize, XSUM_U32 seed)
133 {
134 (void)seed;
135 return (XSUM_U32)XXH3_64bits(buffer, bufferSize);
136 }
137 static XSUM_U32 localXXH3_64b_seeded(const void* buffer, size_t bufferSize, XSUM_U32 seed)
138 {
139 return (XSUM_U32)XXH3_64bits_withSeed(buffer, bufferSize, seed);
140 }
141 static XSUM_U32 localXXH3_64b_secret(const void* buffer, size_t bufferSize, XSUM_U32 seed)
142 {
143 (void)seed;
144 return (XSUM_U32)XXH3_64bits_withSecret(buffer, bufferSize, g_benchSecretBuf, sizeof(g_benchSecretBuf));
145 }
146 static XSUM_U32 localXXH3_128b(const void* buffer, size_t bufferSize, XSUM_U32 seed)
147 {
148 (void)seed;
149 return (XSUM_U32)(XXH3_128bits(buffer, bufferSize).low64);
150 }
151 static XSUM_U32 localXXH3_128b_seeded(const void* buffer, size_t bufferSize, XSUM_U32 seed)
152 {
153 return (XSUM_U32)(XXH3_128bits_withSeed(buffer, bufferSize, seed).low64);
154 }
155 static XSUM_U32 localXXH3_128b_secret(const void* buffer, size_t bufferSize, XSUM_U32 seed)
156 {
157 (void)seed;
158 return (XSUM_U32)(XXH3_128bits_withSecret(buffer, bufferSize, g_benchSecretBuf, sizeof(g_benchSecretBuf)).low64);
159 }
160 static XSUM_U32 localXXH3_stream(const void* buffer, size_t bufferSize, XSUM_U32 seed)
161 {
162 XXH3_state_t state;
163 (void)seed;
164 XXH3_64bits_reset(&state);
165 XXH3_64bits_update(&state, buffer, bufferSize);
166 return (XSUM_U32)XXH3_64bits_digest(&state);
167 }
168 static XSUM_U32 localXXH3_stream_seeded(const void* buffer, size_t bufferSize, XSUM_U32 seed)
169 {
170 XXH3_state_t state;
171 XXH3_INITSTATE(&state);
172 XXH3_64bits_reset_withSeed(&state, (XXH64_hash_t)seed);
173 XXH3_64bits_update(&state, buffer, bufferSize);
174 return (XSUM_U32)XXH3_64bits_digest(&state);
175 }
176 static XSUM_U32 localXXH128_stream(const void* buffer, size_t bufferSize, XSUM_U32 seed)
177 {
178 XXH3_state_t state;
179 (void)seed;
180 XXH3_128bits_reset(&state);
181 XXH3_128bits_update(&state, buffer, bufferSize);
182 return (XSUM_U32)(XXH3_128bits_digest(&state).low64);
183 }
184 static XSUM_U32 localXXH128_stream_seeded(const void* buffer, size_t bufferSize, XSUM_U32 seed)
185 {
186 XXH3_state_t state;
187 XXH3_INITSTATE(&state);
188 XXH3_128bits_reset_withSeed(&state, (XXH64_hash_t)seed);
189 XXH3_128bits_update(&state, buffer, bufferSize);
190 return (XSUM_U32)(XXH3_128bits_digest(&state).low64);
191 }
192
193
194 typedef struct {
195 const char* name;
196 hashFunction func;
197 } hashInfo;
198
199 static const hashInfo g_hashesToBench[] = {
200 { "XXH32", &localXXH32 },
201 { "XXH64", &localXXH64 },
202 { "XXH3_64b", &localXXH3_64b },
203 { "XXH3_64b w/seed", &localXXH3_64b_seeded },
204 { "XXH3_64b w/secret", &localXXH3_64b_secret },
205 { "XXH128", &localXXH3_128b },
206 { "XXH128 w/seed", &localXXH3_128b_seeded },
207 { "XXH128 w/secret", &localXXH3_128b_secret },
208 { "XXH32_stream", &localXXH32_stream },
209 { "XXH64_stream", &localXXH64_stream },
210 { "XXH3_stream", &localXXH3_stream },
211 { "XXH3_stream w/seed",&localXXH3_stream_seeded },
212 { "XXH128_stream", &localXXH128_stream },
213 { "XXH128_stream w/seed",&localXXH128_stream_seeded },
214 };
215 #define NB_HASHFUNC (sizeof(g_hashesToBench) / sizeof(*g_hashesToBench))
216
217 #define NB_TESTFUNC (1 + 2 * NB_HASHFUNC)
218 int const g_nbTestFunctions = NB_TESTFUNC;
219 char g_testIDs[NB_TESTFUNC] = { 0 };
220 const char k_testIDs_default[NB_TESTFUNC] = { 0,
221 1 /*XXH32*/, 0,
222 1 /*XXH64*/, 0,
223 1 /*XXH3*/, 0, 0, 0, 0, 0,
224 1 /*XXH128*/ };
225
226 int g_nbIterations = NBLOOPS_DEFAULT;
227 #define HASHNAME_MAX 29
228 static void XSUM_benchHash(hashFunction h, const char* hName, int testID,
229 const void* buffer, size_t bufferSize)
230 {
231 XSUM_U32 nbh_perIteration = (XSUM_U32)((XXH_1ST_SPEED_TARGET MB) / (bufferSize+1)) + 1;
232 int iterationNb, nbIterations = g_nbIterations + !g_nbIterations /* min 1 */;
233 double fastestH = 100000000.;
234 assert(HASHNAME_MAX > 2);
235 XSUM_logVerbose(2, "\r%80s\r", ""); /* Clean display line */
236
237 for (iterationNb = 1; iterationNb <= nbIterations; iterationNb++) {
238 XSUM_U32 r=0;
239 clock_t cStart;
240
241 XSUM_logVerbose(2, "%2i-%-*.*s : %10u ->\r",
242 iterationNb,
243 HASHNAME_MAX, HASHNAME_MAX, hName,
244 (unsigned)bufferSize);
245 cStart = clock();
246 while (clock() == cStart); /* starts clock() at its exact beginning */
247 cStart = clock();
248
249 { XSUM_U32 u;
250 for (u=0; u<nbh_perIteration; u++)
251 r += h(buffer, bufferSize, u);
252 }
253 if (r==0) XSUM_logVerbose(3,".\r"); /* do something with r to defeat compiler "optimizing" hash away */
254
255 { clock_t const nbTicks = XSUM_clockSpan(cStart);
256 double const ticksPerHash = ((double)nbTicks / TIMELOOP) / nbh_perIteration;
257 /*
258 * clock() is the only decent portable timer, but it isn't very
259 * precise.
260 *
261 * Sometimes, this lack of precision is enough that the benchmark
262 * finishes before there are enough ticks to get a meaningful result.
263 *
264 * For example, on a Core 2 Duo (without any sort of Turbo Boost),
265 * the imprecise timer caused peculiar results like so:
266 *
267 * XXH3_64b 4800.0 MB/s // conveniently even
268 * XXH3_64b unaligned 4800.0 MB/s
269 * XXH3_64b seeded 9600.0 MB/s // magical 2x speedup?!
270 * XXH3_64b seeded unaligned 4800.0 MB/s
271 *
272 * If we sense a suspiciously low number of ticks, we increase the
273 * iterations until we can get something meaningful.
274 */
275 if (nbTicks < TIMELOOP_MIN) {
276 /* Not enough time spent in benchmarking, risk of rounding bias */
277 if (nbTicks == 0) { /* faster than resolution timer */
278 nbh_perIteration *= 100;
279 } else {
280 /*
281 * update nbh_perIteration so that the next round lasts
282 * approximately 1 second.
283 */
284 double nbh_perSecond = (1 / ticksPerHash) + 1;
285 if (nbh_perSecond > (double)(4000U<<20)) nbh_perSecond = (double)(4000U<<20); /* avoid overflow */
286 nbh_perIteration = (XSUM_U32)nbh_perSecond;
287 }
288 /* g_nbIterations==0 => quick evaluation, no claim of accuracy */
289 if (g_nbIterations>0) {
290 iterationNb--; /* new round for a more accurate speed evaluation */
291 continue;
292 }
293 }
294 if (ticksPerHash < fastestH) fastestH = ticksPerHash;
295 if (fastestH>0.) { /* avoid div by zero */
296 XSUM_logVerbose(2, "%2i-%-*.*s : %10u -> %8.0f it/s (%7.1f MB/s) \r",
297 iterationNb,
298 HASHNAME_MAX, HASHNAME_MAX, hName,
299 (unsigned)bufferSize,
300 (double)1 / fastestH,
301 ((double)bufferSize / (1 MB)) / fastestH);
302 } }
303 { double nbh_perSecond = (1 / fastestH) + 1;
304 if (nbh_perSecond > (double)(4000U<<20)) nbh_perSecond = (double)(4000U<<20); /* avoid overflow */
305 nbh_perIteration = (XSUM_U32)nbh_perSecond;
306 }
307 }
308 XSUM_logVerbose(1, "%2i#%-*.*s : %10u -> %8.0f it/s (%7.1f MB/s) \n",
309 testID,
310 HASHNAME_MAX, HASHNAME_MAX, hName,
311 (unsigned)bufferSize,
312 (double)1 / fastestH,
313 ((double)bufferSize / (1 MB)) / fastestH);
314 if (XSUM_logLevel<1)
315 XSUM_logVerbose(0, "%u, ", (unsigned)((double)1 / fastestH));
316 }
317
318
319 /*
320 * Allocates a string containing s1 and s2 concatenated. Acts like strdup.
321 * The result must be freed.
322 */
323 static char* XSUM_strcatDup(const char* s1, const char* s2)
324 {
325 assert(s1 != NULL);
326 assert(s2 != NULL);
327 { size_t len1 = strlen(s1);
328 size_t len2 = strlen(s2);
329 char* buf = (char*)malloc(len1 + len2 + 1);
330 if (buf != NULL) {
331 /* strcpy(buf, s1) */
332 memcpy(buf, s1, len1);
333 /* strcat(buf, s2) */
334 memcpy(buf + len1, s2, len2 + 1);
335 }
336 return buf;
337 }
338 }
339
340
341 /*!
342 * XSUM_benchMem():
343 * Benchmark provided content up to twice per function:
344 * - once at provided aligned memory address (%16)
345 * - second time at unaligned memory address (+3)
346 * Enabled functions and modes are provided via @g_hashesToBench global variable.
347 * @buffer: Must be 16-byte aligned.
348 * The allocated size of underlying @buffer must be >= (@bufferSize+3).
349 * This function also fills @g_benchSecretBuf, to bench XXH3's _withSecret() variants.
350 */
351 static void XSUM_benchMem(const void* buffer, size_t bufferSize)
352 {
353 assert((((size_t)buffer) & 15) == 0); /* ensure alignment */
354 XSUM_fillTestBuffer(g_benchSecretBuf, sizeof(g_benchSecretBuf));
355 { int i;
356 for (i = 1; i < (int)NB_TESTFUNC; i++) {
357 int const hashFuncID = (i-1) / 2;
358 assert(g_hashesToBench[hashFuncID].name != NULL);
359 if (g_testIDs[i] == 0) continue;
360 /* aligned */
361 if ((i % 2) == 1) {
362 XSUM_benchHash(g_hashesToBench[hashFuncID].func, g_hashesToBench[hashFuncID].name, i, buffer, bufferSize);
363 }
364 /* unaligned */
365 if ((i % 2) == 0) {
366 /* Append "unaligned". */
367 char* const hashNameBuf = XSUM_strcatDup(g_hashesToBench[hashFuncID].name, " unaligned");
368 assert(hashNameBuf != NULL);
369 XSUM_benchHash(g_hashesToBench[hashFuncID].func, hashNameBuf, i, ((const char*)buffer)+3, bufferSize);
370 free(hashNameBuf);
371 }
372 } }
373 }
374
375 static size_t XSUM_selectBenchedSize(const char* fileName)
376 {
377 XSUM_U64 const inFileSize = XSUM_getFileSize(fileName);
378 size_t benchedSize = (size_t) XSUM_findMaxMem(inFileSize);
379 if ((XSUM_U64)benchedSize > inFileSize) benchedSize = (size_t)inFileSize;
380 if (benchedSize < inFileSize) {
381 XSUM_log("Not enough memory for '%s' full size; testing %i MB only...\n", fileName, (int)(benchedSize>>20));
382 }
383 return benchedSize;
384 }
385
386
387 int XSUM_benchFiles(const char* fileNamesTable[], int nbFiles)
388 {
389 int fileIdx;
390 for (fileIdx=0; fileIdx<nbFiles; fileIdx++) {
391 const char* const inFileName = fileNamesTable[fileIdx];
392 assert(inFileName != NULL);
393
394 { FILE* const inFile = XSUM_fopen( inFileName, "rb" );
395 size_t const benchedSize = XSUM_selectBenchedSize(inFileName);
396 char* const buffer = (char*)calloc(benchedSize+16+3, 1);
397 void* const alignedBuffer = (buffer+15) - (((size_t)(buffer+15)) & 0xF); /* align on next 16 bytes */
398
399 /* Checks */
400 if (inFile==NULL){
401 XSUM_log("Error: Could not open '%s': %s.\n", inFileName, strerror(errno));
402 free(buffer);
403 exit(11);
404 }
405 if(!buffer) {
406 XSUM_log("\nError: Out of memory.\n");
407 fclose(inFile);
408 exit(12);
409 }
410
411 /* Fill input buffer */
412 { size_t const readSize = fread(alignedBuffer, 1, benchedSize, inFile);
413 fclose(inFile);
414 if(readSize != benchedSize) {
415 XSUM_log("\nError: Could not read '%s': %s.\n", inFileName, strerror(errno));
416 free(buffer);
417 exit(13);
418 } }
419
420 /* bench */
421 XSUM_benchMem(alignedBuffer, benchedSize);
422
423 free(buffer);
424 } }
425 return 0;
426 }
427
428
429 int XSUM_benchInternal(size_t keySize)
430 {
431 void* const buffer = calloc(keySize+16+3, 1);
432 if (buffer == NULL) {
433 XSUM_log("\nError: Out of memory.\n");
434 exit(12);
435 }
436
437 { const void* const alignedBuffer = ((char*)buffer+15) - (((size_t)((char*)buffer+15)) & 0xF); /* align on next 16 bytes */
438
439 /* bench */
440 XSUM_logVerbose(1, "Sample of ");
441 if (keySize > 10 KB) {
442 XSUM_logVerbose(1, "%u KB", (unsigned)(keySize >> 10));
443 } else {
444 XSUM_logVerbose(1, "%u bytes", (unsigned)keySize);
445 }
446 XSUM_logVerbose(1, "... \n");
447
448 XSUM_benchMem(alignedBuffer, keySize);
449 free(buffer);
450 }
451 return 0;
452 }