1 /*
2 * Copyright (c) Yann Collet, Facebook, Inc.
3 * All rights reserved.
4 *
5 * This source code is licensed under both the BSD-style license (found in the
6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7 * in the COPYING file in the root directory of this source tree).
8 * You may select, at your option, one of the above-listed licenses.
9 */
10
11
12 /* **************************************
13 * Tuning parameters
14 ****************************************/
15 #ifndef BMK_TIMETEST_DEFAULT_S /* default minimum time per test */
16 #define BMK_TIMETEST_DEFAULT_S 3
17 #endif
18
19
20 /* *************************************
21 * Includes
22 ***************************************/
23 #include "platform.h" /* Large Files support */
24 #include "util.h" /* UTIL_getFileSize, UTIL_sleep */
25 #include <stdlib.h> /* malloc, free */
26 #include <string.h> /* memset, strerror */
27 #include <stdio.h> /* fprintf, fopen */
28 #include <errno.h>
29 #include <assert.h> /* assert */
30
31 #include "timefn.h" /* UTIL_time_t */
32 #include "benchfn.h"
33 #include "../lib/common/mem.h"
34 #define ZSTD_STATIC_LINKING_ONLY
35 #include "../lib/zstd.h"
36 #include "datagen.h" /* RDG_genBuffer */
37 #include "../lib/common/xxhash.h"
38 #include "benchzstd.h"
39 #include "../lib/zstd_errors.h"
40
41
42 /* *************************************
43 * Constants
44 ***************************************/
45 #ifndef ZSTD_GIT_COMMIT
46 # define ZSTD_GIT_COMMIT_STRING ""
47 #else
48 # define ZSTD_GIT_COMMIT_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_GIT_COMMIT)
49 #endif
50
51 #define TIMELOOP_MICROSEC (1*1000000ULL) /* 1 second */
52 #define TIMELOOP_NANOSEC (1*1000000000ULL) /* 1 second */
53 #define ACTIVEPERIOD_MICROSEC (70*TIMELOOP_MICROSEC) /* 70 seconds */
54 #define COOLPERIOD_SEC 10
55
56 #define KB *(1 <<10)
57 #define MB *(1 <<20)
58 #define GB *(1U<<30)
59
60 #define BMK_RUNTEST_DEFAULT_MS 1000
61
62 static const size_t maxMemory = (sizeof(size_t)==4) ?
63 /* 32-bit */ (2 GB - 64 MB) :
64 /* 64-bit */ (size_t)(1ULL << ((sizeof(size_t)*8)-31));
65
66
67 /* *************************************
68 * console display
69 ***************************************/
70 #define DISPLAY(...) { fprintf(stderr, __VA_ARGS__); fflush(NULL); }
71 #define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
72 /* 0 : no display; 1: errors; 2 : + result + interaction + warnings; 3 : + progression; 4 : + information */
73 #define OUTPUT(...) { fprintf(stdout, __VA_ARGS__); fflush(NULL); }
74 #define OUTPUTLEVEL(l, ...) if (displayLevel>=l) { OUTPUT(__VA_ARGS__); }
75
76
77 /* *************************************
78 * Exceptions
79 ***************************************/
80 #ifndef DEBUG
81 # define DEBUG 0
82 #endif
83 #define DEBUGOUTPUT(...) { if (DEBUG) DISPLAY(__VA_ARGS__); }
84
85 #define RETURN_ERROR_INT(errorNum, ...) { \
86 DEBUGOUTPUT("%s: %i: \n", __FILE__, __LINE__); \
87 DISPLAYLEVEL(1, "Error %i : ", errorNum); \
88 DISPLAYLEVEL(1, __VA_ARGS__); \
89 DISPLAYLEVEL(1, " \n"); \
90 return errorNum; \
91 }
92
93 #define CHECK_Z(zf) { \
94 size_t const zerr = zf; \
95 if (ZSTD_isError(zerr)) { \
96 DEBUGOUTPUT("%s: %i: \n", __FILE__, __LINE__); \
97 DISPLAY("Error : "); \
98 DISPLAY("%s failed : %s", \
99 #zf, ZSTD_getErrorName(zerr)); \
100 DISPLAY(" \n"); \
101 exit(1); \
102 } \
103 }
104
105 #define RETURN_ERROR(errorNum, retType, ...) { \
106 retType r; \
107 memset(&r, 0, sizeof(retType)); \
108 DEBUGOUTPUT("%s: %i: \n", __FILE__, __LINE__); \
109 DISPLAYLEVEL(1, "Error %i : ", errorNum); \
110 DISPLAYLEVEL(1, __VA_ARGS__); \
111 DISPLAYLEVEL(1, " \n"); \
112 r.tag = errorNum; \
113 return r; \
114 }
115
116
117 /* *************************************
118 * Benchmark Parameters
119 ***************************************/
120
BMK_initAdvancedParams(void)121 BMK_advancedParams_t BMK_initAdvancedParams(void) {
122 BMK_advancedParams_t const res = {
123 BMK_both, /* mode */
124 BMK_TIMETEST_DEFAULT_S, /* nbSeconds */
125 0, /* blockSize */
126 0, /* nbWorkers */
127 0, /* realTime */
128 0, /* additionalParam */
129 0, /* ldmFlag */
130 0, /* ldmMinMatch */
131 0, /* ldmHashLog */
132 0, /* ldmBuckSizeLog */
133 0, /* ldmHashRateLog */
134 ZSTD_ps_auto, /* literalCompressionMode */
135 0 /* useRowMatchFinder */
136 };
137 return res;
138 }
139
140
141 /* ********************************************************
142 * Bench functions
143 **********************************************************/
144 typedef struct {
145 const void* srcPtr;
146 size_t srcSize;
147 void* cPtr;
148 size_t cRoom;
149 size_t cSize;
150 void* resPtr;
151 size_t resSize;
152 } blockParam_t;
153
154 #undef MIN
155 #undef MAX
156 #define MIN(a,b) ((a) < (b) ? (a) : (b))
157 #define MAX(a,b) ((a) > (b) ? (a) : (b))
158
159 static void
BMK_initCCtx(ZSTD_CCtx * ctx,const void * dictBuffer,size_t dictBufferSize,int cLevel,const ZSTD_compressionParameters * comprParams,const BMK_advancedParams_t * adv)160 BMK_initCCtx(ZSTD_CCtx* ctx,
161 const void* dictBuffer, size_t dictBufferSize,
162 int cLevel,
163 const ZSTD_compressionParameters* comprParams,
164 const BMK_advancedParams_t* adv)
165 {
166 ZSTD_CCtx_reset(ctx, ZSTD_reset_session_and_parameters);
167 if (adv->nbWorkers==1) {
168 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_nbWorkers, 0));
169 } else {
170 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_nbWorkers, adv->nbWorkers));
171 }
172 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_compressionLevel, cLevel));
173 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_useRowMatchFinder, adv->useRowMatchFinder));
174 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_enableLongDistanceMatching, adv->ldmFlag));
175 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_ldmMinMatch, adv->ldmMinMatch));
176 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_ldmHashLog, adv->ldmHashLog));
177 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_ldmBucketSizeLog, adv->ldmBucketSizeLog));
178 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_ldmHashRateLog, adv->ldmHashRateLog));
179 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_windowLog, (int)comprParams->windowLog));
180 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_hashLog, (int)comprParams->hashLog));
181 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_chainLog, (int)comprParams->chainLog));
182 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_searchLog, (int)comprParams->searchLog));
183 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_minMatch, (int)comprParams->minMatch));
184 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_targetLength, (int)comprParams->targetLength));
185 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_literalCompressionMode, (int)adv->literalCompressionMode));
186 CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_strategy, (int)comprParams->strategy));
187 CHECK_Z(ZSTD_CCtx_loadDictionary(ctx, dictBuffer, dictBufferSize));
188 }
189
BMK_initDCtx(ZSTD_DCtx * dctx,const void * dictBuffer,size_t dictBufferSize)190 static void BMK_initDCtx(ZSTD_DCtx* dctx,
191 const void* dictBuffer, size_t dictBufferSize) {
192 CHECK_Z(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters));
193 CHECK_Z(ZSTD_DCtx_loadDictionary(dctx, dictBuffer, dictBufferSize));
194 }
195
196
197 typedef struct {
198 ZSTD_CCtx* cctx;
199 const void* dictBuffer;
200 size_t dictBufferSize;
201 int cLevel;
202 const ZSTD_compressionParameters* comprParams;
203 const BMK_advancedParams_t* adv;
204 } BMK_initCCtxArgs;
205
local_initCCtx(void * payload)206 static size_t local_initCCtx(void* payload) {
207 BMK_initCCtxArgs* ag = (BMK_initCCtxArgs*)payload;
208 BMK_initCCtx(ag->cctx, ag->dictBuffer, ag->dictBufferSize, ag->cLevel, ag->comprParams, ag->adv);
209 return 0;
210 }
211
212 typedef struct {
213 ZSTD_DCtx* dctx;
214 const void* dictBuffer;
215 size_t dictBufferSize;
216 } BMK_initDCtxArgs;
217
local_initDCtx(void * payload)218 static size_t local_initDCtx(void* payload) {
219 BMK_initDCtxArgs* ag = (BMK_initDCtxArgs*)payload;
220 BMK_initDCtx(ag->dctx, ag->dictBuffer, ag->dictBufferSize);
221 return 0;
222 }
223
224
225 /* `addArgs` is the context */
local_defaultCompress(const void * srcBuffer,size_t srcSize,void * dstBuffer,size_t dstSize,void * addArgs)226 static size_t local_defaultCompress(
227 const void* srcBuffer, size_t srcSize,
228 void* dstBuffer, size_t dstSize,
229 void* addArgs)
230 {
231 ZSTD_CCtx* const cctx = (ZSTD_CCtx*)addArgs;
232 return ZSTD_compress2(cctx, dstBuffer, dstSize, srcBuffer, srcSize);
233 }
234
235 /* `addArgs` is the context */
local_defaultDecompress(const void * srcBuffer,size_t srcSize,void * dstBuffer,size_t dstCapacity,void * addArgs)236 static size_t local_defaultDecompress(
237 const void* srcBuffer, size_t srcSize,
238 void* dstBuffer, size_t dstCapacity,
239 void* addArgs)
240 {
241 size_t moreToFlush = 1;
242 ZSTD_DCtx* const dctx = (ZSTD_DCtx*)addArgs;
243 ZSTD_inBuffer in;
244 ZSTD_outBuffer out;
245 in.src = srcBuffer; in.size = srcSize; in.pos = 0;
246 out.dst = dstBuffer; out.size = dstCapacity; out.pos = 0;
247 while (moreToFlush) {
248 if(out.pos == out.size) {
249 return (size_t)-ZSTD_error_dstSize_tooSmall;
250 }
251 moreToFlush = ZSTD_decompressStream(dctx, &out, &in);
252 if (ZSTD_isError(moreToFlush)) {
253 return moreToFlush;
254 }
255 }
256 return out.pos;
257
258 }
259
260
261 /* ================================================================= */
262 /* Benchmark Zstandard, mem-to-mem scenarios */
263 /* ================================================================= */
264
BMK_isSuccessful_benchOutcome(BMK_benchOutcome_t outcome)265 int BMK_isSuccessful_benchOutcome(BMK_benchOutcome_t outcome)
266 {
267 return outcome.tag == 0;
268 }
269
BMK_extract_benchResult(BMK_benchOutcome_t outcome)270 BMK_benchResult_t BMK_extract_benchResult(BMK_benchOutcome_t outcome)
271 {
272 assert(outcome.tag == 0);
273 return outcome.internal_never_use_directly;
274 }
275
BMK_benchOutcome_error(void)276 static BMK_benchOutcome_t BMK_benchOutcome_error(void)
277 {
278 BMK_benchOutcome_t b;
279 memset(&b, 0, sizeof(b));
280 b.tag = 1;
281 return b;
282 }
283
BMK_benchOutcome_setValidResult(BMK_benchResult_t result)284 static BMK_benchOutcome_t BMK_benchOutcome_setValidResult(BMK_benchResult_t result)
285 {
286 BMK_benchOutcome_t b;
287 b.tag = 0;
288 b.internal_never_use_directly = result;
289 return b;
290 }
291
292
293 /* benchMem with no allocation */
294 static BMK_benchOutcome_t
BMK_benchMemAdvancedNoAlloc(const void ** srcPtrs,size_t * srcSizes,void ** cPtrs,size_t * cCapacities,size_t * cSizes,void ** resPtrs,size_t * resSizes,void ** resultBufferPtr,void * compressedBuffer,size_t maxCompressedSize,BMK_timedFnState_t * timeStateCompress,BMK_timedFnState_t * timeStateDecompress,const void * srcBuffer,size_t srcSize,const size_t * fileSizes,unsigned nbFiles,const int cLevel,const ZSTD_compressionParameters * comprParams,const void * dictBuffer,size_t dictBufferSize,ZSTD_CCtx * cctx,ZSTD_DCtx * dctx,int displayLevel,const char * displayName,const BMK_advancedParams_t * adv)295 BMK_benchMemAdvancedNoAlloc(
296 const void** srcPtrs, size_t* srcSizes,
297 void** cPtrs, size_t* cCapacities, size_t* cSizes,
298 void** resPtrs, size_t* resSizes,
299 void** resultBufferPtr, void* compressedBuffer,
300 size_t maxCompressedSize,
301 BMK_timedFnState_t* timeStateCompress,
302 BMK_timedFnState_t* timeStateDecompress,
303
304 const void* srcBuffer, size_t srcSize,
305 const size_t* fileSizes, unsigned nbFiles,
306 const int cLevel,
307 const ZSTD_compressionParameters* comprParams,
308 const void* dictBuffer, size_t dictBufferSize,
309 ZSTD_CCtx* cctx, ZSTD_DCtx* dctx,
310 int displayLevel, const char* displayName,
311 const BMK_advancedParams_t* adv)
312 {
313 size_t const blockSize = ((adv->blockSize>=32 && (adv->mode != BMK_decodeOnly)) ? adv->blockSize : srcSize) + (!srcSize); /* avoid div by 0 */
314 BMK_benchResult_t benchResult;
315 size_t const loadedCompressedSize = srcSize;
316 size_t cSize = 0;
317 double ratio = 0.;
318 U32 nbBlocks;
319
320 assert(cctx != NULL); assert(dctx != NULL);
321
322 /* init */
323 memset(&benchResult, 0, sizeof(benchResult));
324 if (strlen(displayName)>17) displayName += strlen(displayName) - 17; /* display last 17 characters */
325 if (adv->mode == BMK_decodeOnly) { /* benchmark only decompression : source must be already compressed */
326 const char* srcPtr = (const char*)srcBuffer;
327 U64 totalDSize64 = 0;
328 U32 fileNb;
329 for (fileNb=0; fileNb<nbFiles; fileNb++) {
330 U64 const fSize64 = ZSTD_findDecompressedSize(srcPtr, fileSizes[fileNb]);
331 if (fSize64==0) RETURN_ERROR(32, BMK_benchOutcome_t, "Impossible to determine original size ");
332 totalDSize64 += fSize64;
333 srcPtr += fileSizes[fileNb];
334 }
335 { size_t const decodedSize = (size_t)totalDSize64;
336 assert((U64)decodedSize == totalDSize64); /* check overflow */
337 free(*resultBufferPtr);
338 *resultBufferPtr = malloc(decodedSize);
339 if (!(*resultBufferPtr)) {
340 RETURN_ERROR(33, BMK_benchOutcome_t, "not enough memory");
341 }
342 if (totalDSize64 > decodedSize) { /* size_t overflow */
343 free(*resultBufferPtr);
344 RETURN_ERROR(32, BMK_benchOutcome_t, "original size is too large");
345 }
346 cSize = srcSize;
347 srcSize = decodedSize;
348 ratio = (double)srcSize / (double)cSize;
349 }
350 }
351
352 /* Init data blocks */
353 { const char* srcPtr = (const char*)srcBuffer;
354 char* cPtr = (char*)compressedBuffer;
355 char* resPtr = (char*)(*resultBufferPtr);
356 U32 fileNb;
357 for (nbBlocks=0, fileNb=0; fileNb<nbFiles; fileNb++) {
358 size_t remaining = fileSizes[fileNb];
359 U32 const nbBlocksforThisFile = (adv->mode == BMK_decodeOnly) ? 1 : (U32)((remaining + (blockSize-1)) / blockSize);
360 U32 const blockEnd = nbBlocks + nbBlocksforThisFile;
361 for ( ; nbBlocks<blockEnd; nbBlocks++) {
362 size_t const thisBlockSize = MIN(remaining, blockSize);
363 srcPtrs[nbBlocks] = srcPtr;
364 srcSizes[nbBlocks] = thisBlockSize;
365 cPtrs[nbBlocks] = cPtr;
366 cCapacities[nbBlocks] = (adv->mode == BMK_decodeOnly) ? thisBlockSize : ZSTD_compressBound(thisBlockSize);
367 resPtrs[nbBlocks] = resPtr;
368 resSizes[nbBlocks] = (adv->mode == BMK_decodeOnly) ? (size_t) ZSTD_findDecompressedSize(srcPtr, thisBlockSize) : thisBlockSize;
369 srcPtr += thisBlockSize;
370 cPtr += cCapacities[nbBlocks];
371 resPtr += thisBlockSize;
372 remaining -= thisBlockSize;
373 if (adv->mode == BMK_decodeOnly) {
374 cSizes[nbBlocks] = thisBlockSize;
375 benchResult.cSize = thisBlockSize;
376 } } } }
377
378 /* warming up `compressedBuffer` */
379 if (adv->mode == BMK_decodeOnly) {
380 memcpy(compressedBuffer, srcBuffer, loadedCompressedSize);
381 } else {
382 RDG_genBuffer(compressedBuffer, maxCompressedSize, 0.10, 0.50, 1);
383 }
384
385 /* Bench */
386 { U64 const crcOrig = (adv->mode == BMK_decodeOnly) ? 0 : XXH64(srcBuffer, srcSize, 0);
387 # define NB_MARKS 4
388 const char* marks[NB_MARKS] = { " |", " /", " =", " \\" };
389 U32 markNb = 0;
390 int compressionCompleted = (adv->mode == BMK_decodeOnly);
391 int decompressionCompleted = (adv->mode == BMK_compressOnly);
392 BMK_benchParams_t cbp, dbp;
393 BMK_initCCtxArgs cctxprep;
394 BMK_initDCtxArgs dctxprep;
395
396 cbp.benchFn = local_defaultCompress; /* ZSTD_compress2 */
397 cbp.benchPayload = cctx;
398 cbp.initFn = local_initCCtx; /* BMK_initCCtx */
399 cbp.initPayload = &cctxprep;
400 cbp.errorFn = ZSTD_isError;
401 cbp.blockCount = nbBlocks;
402 cbp.srcBuffers = srcPtrs;
403 cbp.srcSizes = srcSizes;
404 cbp.dstBuffers = cPtrs;
405 cbp.dstCapacities = cCapacities;
406 cbp.blockResults = cSizes;
407
408 cctxprep.cctx = cctx;
409 cctxprep.dictBuffer = dictBuffer;
410 cctxprep.dictBufferSize = dictBufferSize;
411 cctxprep.cLevel = cLevel;
412 cctxprep.comprParams = comprParams;
413 cctxprep.adv = adv;
414
415 dbp.benchFn = local_defaultDecompress;
416 dbp.benchPayload = dctx;
417 dbp.initFn = local_initDCtx;
418 dbp.initPayload = &dctxprep;
419 dbp.errorFn = ZSTD_isError;
420 dbp.blockCount = nbBlocks;
421 dbp.srcBuffers = (const void* const *) cPtrs;
422 dbp.srcSizes = cSizes;
423 dbp.dstBuffers = resPtrs;
424 dbp.dstCapacities = resSizes;
425 dbp.blockResults = NULL;
426
427 dctxprep.dctx = dctx;
428 dctxprep.dictBuffer = dictBuffer;
429 dctxprep.dictBufferSize = dictBufferSize;
430
431 OUTPUTLEVEL(2, "\r%70s\r", ""); /* blank line */
432 assert(srcSize < UINT_MAX);
433 OUTPUTLEVEL(2, "%2s-%-17.17s :%10u -> \r", marks[markNb], displayName, (unsigned)srcSize);
434
435 while (!(compressionCompleted && decompressionCompleted)) {
436 if (!compressionCompleted) {
437 BMK_runOutcome_t const cOutcome = BMK_benchTimedFn( timeStateCompress, cbp);
438
439 if (!BMK_isSuccessful_runOutcome(cOutcome)) {
440 return BMK_benchOutcome_error();
441 }
442
443 { BMK_runTime_t const cResult = BMK_extract_runTime(cOutcome);
444 cSize = cResult.sumOfReturn;
445 ratio = (double)srcSize / (double)cSize;
446 { BMK_benchResult_t newResult;
447 newResult.cSpeed = (U64)((double)srcSize * TIMELOOP_NANOSEC / cResult.nanoSecPerRun);
448 benchResult.cSize = cSize;
449 if (newResult.cSpeed > benchResult.cSpeed)
450 benchResult.cSpeed = newResult.cSpeed;
451 } }
452
453 { int const ratioAccuracy = (ratio < 10.) ? 3 : 2;
454 assert(cSize < UINT_MAX);
455 OUTPUTLEVEL(2, "%2s-%-17.17s :%10u ->%10u (x%5.*f), %6.*f MB/s \r",
456 marks[markNb], displayName,
457 (unsigned)srcSize, (unsigned)cSize,
458 ratioAccuracy, ratio,
459 benchResult.cSpeed < (10 * MB_UNIT) ? 2 : 1, (double)benchResult.cSpeed / MB_UNIT);
460 }
461 compressionCompleted = BMK_isCompleted_TimedFn(timeStateCompress);
462 }
463
464 if(!decompressionCompleted) {
465 BMK_runOutcome_t const dOutcome = BMK_benchTimedFn(timeStateDecompress, dbp);
466
467 if(!BMK_isSuccessful_runOutcome(dOutcome)) {
468 return BMK_benchOutcome_error();
469 }
470
471 { BMK_runTime_t const dResult = BMK_extract_runTime(dOutcome);
472 U64 const newDSpeed = (U64)((double)srcSize * TIMELOOP_NANOSEC / dResult.nanoSecPerRun);
473 if (newDSpeed > benchResult.dSpeed)
474 benchResult.dSpeed = newDSpeed;
475 }
476
477 { int const ratioAccuracy = (ratio < 10.) ? 3 : 2;
478 OUTPUTLEVEL(2, "%2s-%-17.17s :%10u ->%10u (x%5.*f), %6.*f MB/s, %6.1f MB/s\r",
479 marks[markNb], displayName,
480 (unsigned)srcSize, (unsigned)cSize,
481 ratioAccuracy, ratio,
482 benchResult.cSpeed < (10 * MB_UNIT) ? 2 : 1, (double)benchResult.cSpeed / MB_UNIT,
483 (double)benchResult.dSpeed / MB_UNIT);
484 }
485 decompressionCompleted = BMK_isCompleted_TimedFn(timeStateDecompress);
486 }
487 markNb = (markNb+1) % NB_MARKS;
488 } /* while (!(compressionCompleted && decompressionCompleted)) */
489
490 /* CRC Checking */
491 { const BYTE* resultBuffer = (const BYTE*)(*resultBufferPtr);
492 U64 const crcCheck = XXH64(resultBuffer, srcSize, 0);
493 if ((adv->mode == BMK_both) && (crcOrig!=crcCheck)) {
494 size_t u;
495 DISPLAY("!!! WARNING !!! %14s : Invalid Checksum : %x != %x \n",
496 displayName, (unsigned)crcOrig, (unsigned)crcCheck);
497 for (u=0; u<srcSize; u++) {
498 if (((const BYTE*)srcBuffer)[u] != resultBuffer[u]) {
499 unsigned segNb, bNb, pos;
500 size_t bacc = 0;
501 DISPLAY("Decoding error at pos %u ", (unsigned)u);
502 for (segNb = 0; segNb < nbBlocks; segNb++) {
503 if (bacc + srcSizes[segNb] > u) break;
504 bacc += srcSizes[segNb];
505 }
506 pos = (U32)(u - bacc);
507 bNb = pos / (128 KB);
508 DISPLAY("(sample %u, block %u, pos %u) \n", segNb, bNb, pos);
509 { size_t const lowest = (u>5) ? 5 : u;
510 size_t n;
511 DISPLAY("origin: ");
512 for (n=lowest; n>0; n--)
513 DISPLAY("%02X ", ((const BYTE*)srcBuffer)[u-n]);
514 DISPLAY(" :%02X: ", ((const BYTE*)srcBuffer)[u]);
515 for (n=1; n<3; n++)
516 DISPLAY("%02X ", ((const BYTE*)srcBuffer)[u+n]);
517 DISPLAY(" \n");
518 DISPLAY("decode: ");
519 for (n=lowest; n>0; n--)
520 DISPLAY("%02X ", resultBuffer[u-n]);
521 DISPLAY(" :%02X: ", resultBuffer[u]);
522 for (n=1; n<3; n++)
523 DISPLAY("%02X ", resultBuffer[u+n]);
524 DISPLAY(" \n");
525 }
526 break;
527 }
528 if (u==srcSize-1) { /* should never happen */
529 DISPLAY("no difference detected\n");
530 }
531 } /* for (u=0; u<srcSize; u++) */
532 } /* if ((adv->mode == BMK_both) && (crcOrig!=crcCheck)) */
533 } /* CRC Checking */
534
535 if (displayLevel == 1) { /* hidden display mode -q, used by python speed benchmark */
536 double const cSpeed = (double)benchResult.cSpeed / MB_UNIT;
537 double const dSpeed = (double)benchResult.dSpeed / MB_UNIT;
538 if (adv->additionalParam) {
539 OUTPUT("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s %s (param=%d)\n", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName, adv->additionalParam);
540 } else {
541 OUTPUT("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s %s\n", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName);
542 }
543 }
544
545 OUTPUTLEVEL(2, "%2i#\n", cLevel);
546 } /* Bench */
547
548 benchResult.cMem = (1ULL << (comprParams->windowLog)) + ZSTD_sizeof_CCtx(cctx);
549 return BMK_benchOutcome_setValidResult(benchResult);
550 }
551
BMK_benchMemAdvanced(const void * srcBuffer,size_t srcSize,void * dstBuffer,size_t dstCapacity,const size_t * fileSizes,unsigned nbFiles,int cLevel,const ZSTD_compressionParameters * comprParams,const void * dictBuffer,size_t dictBufferSize,int displayLevel,const char * displayName,const BMK_advancedParams_t * adv)552 BMK_benchOutcome_t BMK_benchMemAdvanced(const void* srcBuffer, size_t srcSize,
553 void* dstBuffer, size_t dstCapacity,
554 const size_t* fileSizes, unsigned nbFiles,
555 int cLevel, const ZSTD_compressionParameters* comprParams,
556 const void* dictBuffer, size_t dictBufferSize,
557 int displayLevel, const char* displayName, const BMK_advancedParams_t* adv)
558
559 {
560 int const dstParamsError = !dstBuffer ^ !dstCapacity; /* must be both NULL or none */
561
562 size_t const blockSize = ((adv->blockSize>=32 && (adv->mode != BMK_decodeOnly)) ? adv->blockSize : srcSize) + (!srcSize) /* avoid div by 0 */ ;
563 U32 const maxNbBlocks = (U32) ((srcSize + (blockSize-1)) / blockSize) + nbFiles;
564
565 /* these are the blockTable parameters, just split up */
566 const void ** const srcPtrs = (const void**)malloc(maxNbBlocks * sizeof(void*));
567 size_t* const srcSizes = (size_t*)malloc(maxNbBlocks * sizeof(size_t));
568
569
570 void ** const cPtrs = (void**)malloc(maxNbBlocks * sizeof(void*));
571 size_t* const cSizes = (size_t*)malloc(maxNbBlocks * sizeof(size_t));
572 size_t* const cCapacities = (size_t*)malloc(maxNbBlocks * sizeof(size_t));
573
574 void ** const resPtrs = (void**)malloc(maxNbBlocks * sizeof(void*));
575 size_t* const resSizes = (size_t*)malloc(maxNbBlocks * sizeof(size_t));
576
577 BMK_timedFnState_t* timeStateCompress = BMK_createTimedFnState(adv->nbSeconds * 1000, BMK_RUNTEST_DEFAULT_MS);
578 BMK_timedFnState_t* timeStateDecompress = BMK_createTimedFnState(adv->nbSeconds * 1000, BMK_RUNTEST_DEFAULT_MS);
579
580 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
581 ZSTD_DCtx* const dctx = ZSTD_createDCtx();
582
583 const size_t maxCompressedSize = dstCapacity ? dstCapacity : ZSTD_compressBound(srcSize) + (maxNbBlocks * 1024);
584
585 void* const internalDstBuffer = dstBuffer ? NULL : malloc(maxCompressedSize);
586 void* const compressedBuffer = dstBuffer ? dstBuffer : internalDstBuffer;
587
588 BMK_benchOutcome_t outcome = BMK_benchOutcome_error(); /* error by default */
589
590 void* resultBuffer = srcSize ? malloc(srcSize) : NULL;
591
592 int allocationincomplete = !srcPtrs || !srcSizes || !cPtrs ||
593 !cSizes || !cCapacities || !resPtrs || !resSizes ||
594 !timeStateCompress || !timeStateDecompress ||
595 !cctx || !dctx ||
596 !compressedBuffer || !resultBuffer;
597
598
599 if (!allocationincomplete && !dstParamsError) {
600 outcome = BMK_benchMemAdvancedNoAlloc(srcPtrs, srcSizes,
601 cPtrs, cCapacities, cSizes,
602 resPtrs, resSizes,
603 &resultBuffer,
604 compressedBuffer, maxCompressedSize,
605 timeStateCompress, timeStateDecompress,
606 srcBuffer, srcSize,
607 fileSizes, nbFiles,
608 cLevel, comprParams,
609 dictBuffer, dictBufferSize,
610 cctx, dctx,
611 displayLevel, displayName, adv);
612 }
613
614 /* clean up */
615 BMK_freeTimedFnState(timeStateCompress);
616 BMK_freeTimedFnState(timeStateDecompress);
617
618 ZSTD_freeCCtx(cctx);
619 ZSTD_freeDCtx(dctx);
620
621 free(internalDstBuffer);
622 free(resultBuffer);
623
624 free((void*)srcPtrs);
625 free(srcSizes);
626 free(cPtrs);
627 free(cSizes);
628 free(cCapacities);
629 free(resPtrs);
630 free(resSizes);
631
632 if(allocationincomplete) {
633 RETURN_ERROR(31, BMK_benchOutcome_t, "allocation error : not enough memory");
634 }
635
636 if(dstParamsError) {
637 RETURN_ERROR(32, BMK_benchOutcome_t, "Dst parameters not coherent");
638 }
639 return outcome;
640 }
641
BMK_benchMem(const void * srcBuffer,size_t srcSize,const size_t * fileSizes,unsigned nbFiles,int cLevel,const ZSTD_compressionParameters * comprParams,const void * dictBuffer,size_t dictBufferSize,int displayLevel,const char * displayName)642 BMK_benchOutcome_t BMK_benchMem(const void* srcBuffer, size_t srcSize,
643 const size_t* fileSizes, unsigned nbFiles,
644 int cLevel, const ZSTD_compressionParameters* comprParams,
645 const void* dictBuffer, size_t dictBufferSize,
646 int displayLevel, const char* displayName) {
647
648 BMK_advancedParams_t const adv = BMK_initAdvancedParams();
649 return BMK_benchMemAdvanced(srcBuffer, srcSize,
650 NULL, 0,
651 fileSizes, nbFiles,
652 cLevel, comprParams,
653 dictBuffer, dictBufferSize,
654 displayLevel, displayName, &adv);
655 }
656
BMK_benchCLevel(const void * srcBuffer,size_t benchedSize,const size_t * fileSizes,unsigned nbFiles,int cLevel,const ZSTD_compressionParameters * comprParams,const void * dictBuffer,size_t dictBufferSize,int displayLevel,const char * displayName,BMK_advancedParams_t const * const adv)657 static BMK_benchOutcome_t BMK_benchCLevel(const void* srcBuffer, size_t benchedSize,
658 const size_t* fileSizes, unsigned nbFiles,
659 int cLevel, const ZSTD_compressionParameters* comprParams,
660 const void* dictBuffer, size_t dictBufferSize,
661 int displayLevel, const char* displayName,
662 BMK_advancedParams_t const * const adv)
663 {
664 const char* pch = strrchr(displayName, '\\'); /* Windows */
665 if (!pch) pch = strrchr(displayName, '/'); /* Linux */
666 if (pch) displayName = pch+1;
667
668 if (adv->realTime) {
669 DISPLAYLEVEL(2, "Note : switching to real-time priority \n");
670 SET_REALTIME_PRIORITY;
671 }
672
673 if (displayLevel == 1 && !adv->additionalParam) /* --quiet mode */
674 OUTPUT("bench %s %s: input %u bytes, %u seconds, %u KB blocks\n",
675 ZSTD_VERSION_STRING, ZSTD_GIT_COMMIT_STRING,
676 (unsigned)benchedSize, adv->nbSeconds, (unsigned)(adv->blockSize>>10));
677
678 return BMK_benchMemAdvanced(srcBuffer, benchedSize,
679 NULL, 0,
680 fileSizes, nbFiles,
681 cLevel, comprParams,
682 dictBuffer, dictBufferSize,
683 displayLevel, displayName, adv);
684 }
685
BMK_syntheticTest(int cLevel,double compressibility,const ZSTD_compressionParameters * compressionParams,int displayLevel,const BMK_advancedParams_t * adv)686 BMK_benchOutcome_t BMK_syntheticTest(int cLevel, double compressibility,
687 const ZSTD_compressionParameters* compressionParams,
688 int displayLevel, const BMK_advancedParams_t* adv)
689 {
690 char name[20] = {0};
691 size_t const benchedSize = 10000000;
692 void* srcBuffer;
693 BMK_benchOutcome_t res;
694
695 if (cLevel > ZSTD_maxCLevel()) {
696 RETURN_ERROR(15, BMK_benchOutcome_t, "Invalid Compression Level");
697 }
698
699 /* Memory allocation */
700 srcBuffer = malloc(benchedSize);
701 if (!srcBuffer) RETURN_ERROR(21, BMK_benchOutcome_t, "not enough memory");
702
703 /* Fill input buffer */
704 RDG_genBuffer(srcBuffer, benchedSize, compressibility, 0.0, 0);
705
706 /* Bench */
707 snprintf (name, sizeof(name), "Synthetic %2u%%", (unsigned)(compressibility*100));
708 res = BMK_benchCLevel(srcBuffer, benchedSize,
709 &benchedSize /* ? */, 1 /* ? */,
710 cLevel, compressionParams,
711 NULL, 0, /* dictionary */
712 displayLevel, name, adv);
713
714 /* clean up */
715 free(srcBuffer);
716
717 return res;
718 }
719
720
721
BMK_findMaxMem(U64 requiredMem)722 static size_t BMK_findMaxMem(U64 requiredMem)
723 {
724 size_t const step = 64 MB;
725 BYTE* testmem = NULL;
726
727 requiredMem = (((requiredMem >> 26) + 1) << 26);
728 requiredMem += step;
729 if (requiredMem > maxMemory) requiredMem = maxMemory;
730
731 do {
732 testmem = (BYTE*)malloc((size_t)requiredMem);
733 requiredMem -= step;
734 } while (!testmem && requiredMem > 0);
735
736 free(testmem);
737 return (size_t)(requiredMem);
738 }
739
740 /*! BMK_loadFiles() :
741 * Loads `buffer` with content of files listed within `fileNamesTable`.
742 * At most, fills `buffer` entirely. */
BMK_loadFiles(void * buffer,size_t bufferSize,size_t * fileSizes,const char * const * fileNamesTable,unsigned nbFiles,int displayLevel)743 static int BMK_loadFiles(void* buffer, size_t bufferSize,
744 size_t* fileSizes,
745 const char* const * fileNamesTable, unsigned nbFiles,
746 int displayLevel)
747 {
748 size_t pos = 0, totalSize = 0;
749 unsigned n;
750 for (n=0; n<nbFiles; n++) {
751 U64 fileSize = UTIL_getFileSize(fileNamesTable[n]); /* last file may be shortened */
752 if (UTIL_isDirectory(fileNamesTable[n])) {
753 DISPLAYLEVEL(2, "Ignoring %s directory... \n", fileNamesTable[n]);
754 fileSizes[n] = 0;
755 continue;
756 }
757 if (fileSize == UTIL_FILESIZE_UNKNOWN) {
758 DISPLAYLEVEL(2, "Cannot evaluate size of %s, ignoring ... \n", fileNamesTable[n]);
759 fileSizes[n] = 0;
760 continue;
761 }
762 { FILE* const f = fopen(fileNamesTable[n], "rb");
763 if (f==NULL) RETURN_ERROR_INT(10, "impossible to open file %s", fileNamesTable[n]);
764 OUTPUTLEVEL(2, "Loading %s... \r", fileNamesTable[n]);
765 if (fileSize > bufferSize-pos) fileSize = bufferSize-pos, nbFiles=n; /* buffer too small - stop after this file */
766 { size_t const readSize = fread(((char*)buffer)+pos, 1, (size_t)fileSize, f);
767 if (readSize != (size_t)fileSize) RETURN_ERROR_INT(11, "could not read %s", fileNamesTable[n]);
768 pos += readSize;
769 }
770 fileSizes[n] = (size_t)fileSize;
771 totalSize += (size_t)fileSize;
772 fclose(f);
773 } }
774
775 if (totalSize == 0) RETURN_ERROR_INT(12, "no data to bench");
776 return 0;
777 }
778
BMK_benchFilesAdvanced(const char * const * fileNamesTable,unsigned nbFiles,const char * dictFileName,int cLevel,const ZSTD_compressionParameters * compressionParams,int displayLevel,const BMK_advancedParams_t * adv)779 BMK_benchOutcome_t BMK_benchFilesAdvanced(
780 const char* const * fileNamesTable, unsigned nbFiles,
781 const char* dictFileName, int cLevel,
782 const ZSTD_compressionParameters* compressionParams,
783 int displayLevel, const BMK_advancedParams_t* adv)
784 {
785 void* srcBuffer = NULL;
786 size_t benchedSize;
787 void* dictBuffer = NULL;
788 size_t dictBufferSize = 0;
789 size_t* fileSizes = NULL;
790 BMK_benchOutcome_t res;
791 U64 const totalSizeToLoad = UTIL_getTotalFileSize(fileNamesTable, nbFiles);
792
793 if (!nbFiles) {
794 RETURN_ERROR(14, BMK_benchOutcome_t, "No Files to Benchmark");
795 }
796
797 if (cLevel > ZSTD_maxCLevel()) {
798 RETURN_ERROR(15, BMK_benchOutcome_t, "Invalid Compression Level");
799 }
800
801 if (totalSizeToLoad == UTIL_FILESIZE_UNKNOWN) {
802 RETURN_ERROR(9, BMK_benchOutcome_t, "Error loading files");
803 }
804
805 fileSizes = (size_t*)calloc(nbFiles, sizeof(size_t));
806 if (!fileSizes) RETURN_ERROR(12, BMK_benchOutcome_t, "not enough memory for fileSizes");
807
808 /* Load dictionary */
809 if (dictFileName != NULL) {
810 U64 const dictFileSize = UTIL_getFileSize(dictFileName);
811 if (dictFileSize == UTIL_FILESIZE_UNKNOWN) {
812 DISPLAYLEVEL(1, "error loading %s : %s \n", dictFileName, strerror(errno));
813 free(fileSizes);
814 RETURN_ERROR(9, BMK_benchOutcome_t, "benchmark aborted");
815 }
816 if (dictFileSize > 64 MB) {
817 free(fileSizes);
818 RETURN_ERROR(10, BMK_benchOutcome_t, "dictionary file %s too large", dictFileName);
819 }
820 dictBufferSize = (size_t)dictFileSize;
821 dictBuffer = malloc(dictBufferSize);
822 if (dictBuffer==NULL) {
823 free(fileSizes);
824 RETURN_ERROR(11, BMK_benchOutcome_t, "not enough memory for dictionary (%u bytes)",
825 (unsigned)dictBufferSize);
826 }
827
828 { int const errorCode = BMK_loadFiles(dictBuffer, dictBufferSize,
829 fileSizes, &dictFileName /*?*/,
830 1 /*?*/, displayLevel);
831 if (errorCode) {
832 res = BMK_benchOutcome_error();
833 goto _cleanUp;
834 } }
835 }
836
837 /* Memory allocation & restrictions */
838 benchedSize = BMK_findMaxMem(totalSizeToLoad * 3) / 3;
839 if ((U64)benchedSize > totalSizeToLoad) benchedSize = (size_t)totalSizeToLoad;
840 if (benchedSize < totalSizeToLoad)
841 DISPLAY("Not enough memory; testing %u MB only...\n", (unsigned)(benchedSize >> 20));
842
843 srcBuffer = benchedSize ? malloc(benchedSize) : NULL;
844 if (!srcBuffer) {
845 free(dictBuffer);
846 free(fileSizes);
847 RETURN_ERROR(12, BMK_benchOutcome_t, "not enough memory");
848 }
849
850 /* Load input buffer */
851 { int const errorCode = BMK_loadFiles(srcBuffer, benchedSize,
852 fileSizes, fileNamesTable, nbFiles,
853 displayLevel);
854 if (errorCode) {
855 res = BMK_benchOutcome_error();
856 goto _cleanUp;
857 } }
858
859 /* Bench */
860 { char mfName[20] = {0};
861 snprintf (mfName, sizeof(mfName), " %u files", nbFiles);
862 { const char* const displayName = (nbFiles > 1) ? mfName : fileNamesTable[0];
863 res = BMK_benchCLevel(srcBuffer, benchedSize,
864 fileSizes, nbFiles,
865 cLevel, compressionParams,
866 dictBuffer, dictBufferSize,
867 displayLevel, displayName,
868 adv);
869 } }
870
871 _cleanUp:
872 free(srcBuffer);
873 free(dictBuffer);
874 free(fileSizes);
875 return res;
876 }
877
878
BMK_benchFiles(const char * const * fileNamesTable,unsigned nbFiles,const char * dictFileName,int cLevel,const ZSTD_compressionParameters * compressionParams,int displayLevel)879 BMK_benchOutcome_t BMK_benchFiles(
880 const char* const * fileNamesTable, unsigned nbFiles,
881 const char* dictFileName,
882 int cLevel, const ZSTD_compressionParameters* compressionParams,
883 int displayLevel)
884 {
885 BMK_advancedParams_t const adv = BMK_initAdvancedParams();
886 return BMK_benchFilesAdvanced(fileNamesTable, nbFiles, dictFileName, cLevel, compressionParams, displayLevel, &adv);
887 }
888