1 /* 2 * Copyright (c) 2016-present, Przemyslaw Skibinski, 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 */ 9 10 11 /* ************************************* 12 * Includes 13 ***************************************/ 14 #include "util.h" /* Compiler options, UTIL_GetFileSize, UTIL_sleep */ 15 #include <stdlib.h> /* malloc, free */ 16 #include <string.h> /* memset */ 17 #include <stdio.h> /* fprintf, fopen, ftello64 */ 18 #include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */ 19 #include <ctype.h> /* toupper */ 20 #include <errno.h> /* errno */ 21 22 #include "mem.h" 23 #define ZSTD_STATIC_LINKING_ONLY 24 #include "zstd.h" 25 #include "datagen.h" /* RDG_genBuffer */ 26 #include "xxhash.h" 27 28 #include "zstd_zlibwrapper.h" 29 30 31 32 /*-************************************ 33 * Tuning parameters 34 **************************************/ 35 #ifndef ZSTDCLI_CLEVEL_DEFAULT 36 # define ZSTDCLI_CLEVEL_DEFAULT 3 37 #endif 38 39 40 /*-************************************ 41 * Constants 42 **************************************/ 43 #define COMPRESSOR_NAME "Zstandard wrapper for zlib command line interface" 44 #ifndef ZSTD_VERSION 45 # define ZSTD_VERSION "v" ZSTD_VERSION_STRING 46 #endif 47 #define AUTHOR "Yann Collet" 48 #define WELCOME_MESSAGE "*** %s %i-bits %s, by %s ***\n", COMPRESSOR_NAME, (int)(sizeof(size_t)*8), ZSTD_VERSION, AUTHOR 49 50 #ifndef ZSTD_GIT_COMMIT 51 # define ZSTD_GIT_COMMIT_STRING "" 52 #else 53 # define ZSTD_GIT_COMMIT_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_GIT_COMMIT) 54 #endif 55 56 #define NBLOOPS 3 57 #define TIMELOOP_MICROSEC 1*1000000ULL /* 1 second */ 58 #define ACTIVEPERIOD_MICROSEC 70*1000000ULL /* 70 seconds */ 59 #define COOLPERIOD_SEC 10 60 61 #define KB *(1 <<10) 62 #define MB *(1 <<20) 63 #define GB *(1U<<30) 64 65 static const size_t maxMemory = (sizeof(size_t)==4) ? (2 GB - 64 MB) : (size_t)(1ULL << ((sizeof(size_t)*8)-31)); 66 67 static U32 g_compressibilityDefault = 50; 68 69 70 /* ************************************* 71 * console display 72 ***************************************/ 73 #define DEFAULT_DISPLAY_LEVEL 2 74 #define DISPLAY(...) fprintf(displayOut, __VA_ARGS__) 75 #define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } 76 static int g_displayLevel = DEFAULT_DISPLAY_LEVEL; /* 0 : no display; 1: errors; 2 : + result + interaction + warnings; 3 : + progression; 4 : + information */ 77 static FILE* displayOut; 78 79 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \ 80 if ((clock() - g_time > refreshRate) || (g_displayLevel>=4)) \ 81 { g_time = clock(); DISPLAY(__VA_ARGS__); \ 82 if (g_displayLevel>=4) fflush(displayOut); } } 83 static const clock_t refreshRate = CLOCKS_PER_SEC * 15 / 100; 84 static clock_t g_time = 0; 85 86 87 /* ************************************* 88 * Exceptions 89 ***************************************/ 90 #ifndef DEBUG 91 # define DEBUG 0 92 #endif 93 #define DEBUGOUTPUT(...) { if (DEBUG) DISPLAY(__VA_ARGS__); } 94 #define EXM_THROW(error, ...) \ 95 { \ 96 DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \ 97 DISPLAYLEVEL(1, "Error %i : ", error); \ 98 DISPLAYLEVEL(1, __VA_ARGS__); \ 99 DISPLAYLEVEL(1, "\n"); \ 100 exit(error); \ 101 } 102 103 104 /* ************************************* 105 * Benchmark Parameters 106 ***************************************/ 107 static unsigned g_nbIterations = NBLOOPS; 108 static size_t g_blockSize = 0; 109 int g_additionalParam = 0; 110 111 void BMK_setNotificationLevel(unsigned level) { g_displayLevel=level; } 112 113 void BMK_setAdditionalParam(int additionalParam) { g_additionalParam=additionalParam; } 114 115 void BMK_SetNbIterations(unsigned nbLoops) 116 { 117 g_nbIterations = nbLoops; 118 DISPLAYLEVEL(3, "- test >= %u seconds per compression / decompression -\n", g_nbIterations); 119 } 120 121 void BMK_SetBlockSize(size_t blockSize) 122 { 123 g_blockSize = blockSize; 124 DISPLAYLEVEL(2, "using blocks of size %u KB \n", (unsigned)(blockSize>>10)); 125 } 126 127 128 /* ******************************************************** 129 * Bench functions 130 **********************************************************/ 131 #undef MIN 132 #undef MAX 133 #define MIN(a,b) ((a)<(b) ? (a) : (b)) 134 #define MAX(a,b) ((a)>(b) ? (a) : (b)) 135 136 typedef struct 137 { 138 z_const char* srcPtr; 139 size_t srcSize; 140 char* cPtr; 141 size_t cRoom; 142 size_t cSize; 143 char* resPtr; 144 size_t resSize; 145 } blockParam_t; 146 147 typedef enum { BMK_ZSTD, BMK_ZSTD_STREAM, BMK_ZLIB, BMK_ZWRAP_ZLIB, BMK_ZWRAP_ZSTD, BMK_ZLIB_REUSE, BMK_ZWRAP_ZLIB_REUSE, BMK_ZWRAP_ZSTD_REUSE } BMK_compressor; 148 149 150 static int BMK_benchMem(z_const void* srcBuffer, size_t srcSize, 151 const char* displayName, int cLevel, 152 const size_t* fileSizes, U32 nbFiles, 153 const void* dictBuffer, size_t dictBufferSize, BMK_compressor compressor) 154 { 155 size_t const blockSize = (g_blockSize>=32 ? g_blockSize : srcSize) + (!srcSize) /* avoid div by 0 */ ; 156 size_t const avgSize = MIN(g_blockSize, (srcSize / nbFiles)); 157 U32 const maxNbBlocks = (U32) ((srcSize + (blockSize-1)) / blockSize) + nbFiles; 158 blockParam_t* const blockTable = (blockParam_t*) malloc(maxNbBlocks * sizeof(blockParam_t)); 159 size_t const maxCompressedSize = ZSTD_compressBound(srcSize) + (maxNbBlocks * 1024); /* add some room for safety */ 160 void* const compressedBuffer = malloc(maxCompressedSize); 161 void* const resultBuffer = malloc(srcSize); 162 ZSTD_CCtx* const ctx = ZSTD_createCCtx(); 163 ZSTD_DCtx* const dctx = ZSTD_createDCtx(); 164 U32 nbBlocks; 165 166 /* checks */ 167 if (!compressedBuffer || !resultBuffer || !blockTable || !ctx || !dctx) 168 EXM_THROW(31, "allocation error : not enough memory"); 169 170 /* init */ 171 if (strlen(displayName)>17) displayName += strlen(displayName)-17; /* can only display 17 characters */ 172 173 /* Init blockTable data */ 174 { z_const char* srcPtr = (z_const char*)srcBuffer; 175 char* cPtr = (char*)compressedBuffer; 176 char* resPtr = (char*)resultBuffer; 177 U32 fileNb; 178 for (nbBlocks=0, fileNb=0; fileNb<nbFiles; fileNb++) { 179 size_t remaining = fileSizes[fileNb]; 180 U32 const nbBlocksforThisFile = (U32)((remaining + (blockSize-1)) / blockSize); 181 U32 const blockEnd = nbBlocks + nbBlocksforThisFile; 182 for ( ; nbBlocks<blockEnd; nbBlocks++) { 183 size_t const thisBlockSize = MIN(remaining, blockSize); 184 blockTable[nbBlocks].srcPtr = srcPtr; 185 blockTable[nbBlocks].cPtr = cPtr; 186 blockTable[nbBlocks].resPtr = resPtr; 187 blockTable[nbBlocks].srcSize = thisBlockSize; 188 blockTable[nbBlocks].cRoom = ZSTD_compressBound(thisBlockSize); 189 srcPtr += thisBlockSize; 190 cPtr += blockTable[nbBlocks].cRoom; 191 resPtr += thisBlockSize; 192 remaining -= thisBlockSize; 193 } } } 194 195 /* warmimg up memory */ 196 RDG_genBuffer(compressedBuffer, maxCompressedSize, 0.10, 0.50, 1); 197 198 /* Bench */ 199 { U64 fastestC = (U64)(-1LL), fastestD = (U64)(-1LL); 200 U64 const crcOrig = XXH64(srcBuffer, srcSize, 0); 201 UTIL_time_t coolTime; 202 U64 const maxTime = (g_nbIterations * TIMELOOP_MICROSEC) + 100; 203 U64 totalCTime=0, totalDTime=0; 204 U32 cCompleted=0, dCompleted=0; 205 # define NB_MARKS 4 206 const char* const marks[NB_MARKS] = { " |", " /", " =", "\\" }; 207 U32 markNb = 0; 208 size_t cSize = 0; 209 double ratio = 0.; 210 211 coolTime = UTIL_getTime(); 212 DISPLAYLEVEL(2, "\r%79s\r", ""); 213 while (!cCompleted | !dCompleted) { 214 UTIL_time_t clockStart; 215 U64 clockLoop = g_nbIterations ? TIMELOOP_MICROSEC : 1; 216 217 /* overheat protection */ 218 if (UTIL_clockSpanMicro(coolTime) > ACTIVEPERIOD_MICROSEC) { 219 DISPLAYLEVEL(2, "\rcooling down ... \r"); 220 UTIL_sleep(COOLPERIOD_SEC); 221 coolTime = UTIL_getTime(); 222 } 223 224 /* Compression */ 225 DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->\r", marks[markNb], displayName, (unsigned)srcSize); 226 if (!cCompleted) memset(compressedBuffer, 0xE5, maxCompressedSize); /* warm up and erase result buffer */ 227 228 UTIL_sleepMilli(1); /* give processor time to other processes */ 229 UTIL_waitForNextTick(); 230 clockStart = UTIL_getTime(); 231 232 if (!cCompleted) { /* still some time to do compression tests */ 233 U32 nbLoops = 0; 234 if (compressor == BMK_ZSTD) { 235 ZSTD_parameters const zparams = ZSTD_getParams(cLevel, avgSize, dictBufferSize); 236 ZSTD_customMem const cmem = { NULL, NULL, NULL }; 237 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictBufferSize, ZSTD_dlm_byRef, ZSTD_dct_auto, zparams.cParams, cmem); 238 if (cdict==NULL) EXM_THROW(1, "ZSTD_createCDict_advanced() allocation failure"); 239 240 do { 241 U32 blockNb; 242 size_t rSize; 243 for (blockNb=0; blockNb<nbBlocks; blockNb++) { 244 if (dictBufferSize) { 245 rSize = ZSTD_compress_usingCDict(ctx, 246 blockTable[blockNb].cPtr, blockTable[blockNb].cRoom, 247 blockTable[blockNb].srcPtr,blockTable[blockNb].srcSize, 248 cdict); 249 } else { 250 rSize = ZSTD_compressCCtx (ctx, 251 blockTable[blockNb].cPtr, blockTable[blockNb].cRoom, 252 blockTable[blockNb].srcPtr,blockTable[blockNb].srcSize, cLevel); 253 } 254 if (ZSTD_isError(rSize)) EXM_THROW(1, "ZSTD_compress_usingCDict() failed : %s", ZSTD_getErrorName(rSize)); 255 blockTable[blockNb].cSize = rSize; 256 } 257 nbLoops++; 258 } while (UTIL_clockSpanMicro(clockStart) < clockLoop); 259 ZSTD_freeCDict(cdict); 260 } else if (compressor == BMK_ZSTD_STREAM) { 261 ZSTD_parameters const zparams = ZSTD_getParams(cLevel, avgSize, dictBufferSize); 262 ZSTD_inBuffer inBuffer; 263 ZSTD_outBuffer outBuffer; 264 ZSTD_CStream* zbc = ZSTD_createCStream(); 265 size_t rSize; 266 if (zbc == NULL) EXM_THROW(1, "ZSTD_createCStream() allocation failure"); 267 rSize = ZSTD_initCStream_advanced(zbc, dictBuffer, dictBufferSize, zparams, avgSize); 268 if (ZSTD_isError(rSize)) EXM_THROW(1, "ZSTD_initCStream_advanced() failed : %s", ZSTD_getErrorName(rSize)); 269 do { 270 U32 blockNb; 271 for (blockNb=0; blockNb<nbBlocks; blockNb++) { 272 rSize = ZSTD_resetCStream(zbc, blockTable[blockNb].srcSize); 273 if (ZSTD_isError(rSize)) EXM_THROW(1, "ZSTD_resetCStream() failed : %s", ZSTD_getErrorName(rSize)); 274 inBuffer.src = blockTable[blockNb].srcPtr; 275 inBuffer.size = blockTable[blockNb].srcSize; 276 inBuffer.pos = 0; 277 outBuffer.dst = blockTable[blockNb].cPtr; 278 outBuffer.size = blockTable[blockNb].cRoom; 279 outBuffer.pos = 0; 280 rSize = ZSTD_compressStream(zbc, &outBuffer, &inBuffer); 281 if (ZSTD_isError(rSize)) EXM_THROW(1, "ZSTD_compressStream() failed : %s", ZSTD_getErrorName(rSize)); 282 rSize = ZSTD_endStream(zbc, &outBuffer); 283 if (ZSTD_isError(rSize)) EXM_THROW(1, "ZSTD_endStream() failed : %s", ZSTD_getErrorName(rSize)); 284 blockTable[blockNb].cSize = outBuffer.pos; 285 } 286 nbLoops++; 287 } while (UTIL_clockSpanMicro(clockStart) < clockLoop); 288 ZSTD_freeCStream(zbc); 289 } else if (compressor == BMK_ZWRAP_ZLIB_REUSE || compressor == BMK_ZWRAP_ZSTD_REUSE || compressor == BMK_ZLIB_REUSE) { 290 z_stream def; 291 int ret; 292 int useSetDict = (dictBuffer != NULL); 293 if (compressor == BMK_ZLIB_REUSE || compressor == BMK_ZWRAP_ZLIB_REUSE) ZWRAP_useZSTDcompression(0); 294 else ZWRAP_useZSTDcompression(1); 295 def.zalloc = Z_NULL; 296 def.zfree = Z_NULL; 297 def.opaque = Z_NULL; 298 ret = deflateInit(&def, cLevel); 299 if (ret != Z_OK) EXM_THROW(1, "deflateInit failure"); 300 /* if (ZWRAP_isUsingZSTDcompression()) { 301 ret = ZWRAP_setPledgedSrcSize(&def, avgSize); 302 if (ret != Z_OK) EXM_THROW(1, "ZWRAP_setPledgedSrcSize failure"); 303 } */ 304 do { 305 U32 blockNb; 306 for (blockNb=0; blockNb<nbBlocks; blockNb++) { 307 if (ZWRAP_isUsingZSTDcompression()) 308 ret = ZWRAP_deflateReset_keepDict(&def); /* reuse dictionary to make compression faster */ 309 else 310 ret = deflateReset(&def); 311 if (ret != Z_OK) EXM_THROW(1, "deflateReset failure"); 312 if (useSetDict) { 313 ret = deflateSetDictionary(&def, dictBuffer, dictBufferSize); 314 if (ret != Z_OK) EXM_THROW(1, "deflateSetDictionary failure"); 315 if (ZWRAP_isUsingZSTDcompression()) useSetDict = 0; /* zstd doesn't require deflateSetDictionary after ZWRAP_deflateReset_keepDict */ 316 } 317 def.next_in = (z_const void*) blockTable[blockNb].srcPtr; 318 def.avail_in = (uInt)blockTable[blockNb].srcSize; 319 def.total_in = 0; 320 def.next_out = (void*) blockTable[blockNb].cPtr; 321 def.avail_out = (uInt)blockTable[blockNb].cRoom; 322 def.total_out = 0; 323 ret = deflate(&def, Z_FINISH); 324 if (ret != Z_STREAM_END) EXM_THROW(1, "deflate failure ret=%d srcSize=%d" , ret, (int)blockTable[blockNb].srcSize); 325 blockTable[blockNb].cSize = def.total_out; 326 } 327 nbLoops++; 328 } while (UTIL_clockSpanMicro(clockStart) < clockLoop); 329 ret = deflateEnd(&def); 330 if (ret != Z_OK) EXM_THROW(1, "deflateEnd failure"); 331 } else { 332 z_stream def; 333 if (compressor == BMK_ZLIB || compressor == BMK_ZWRAP_ZLIB) ZWRAP_useZSTDcompression(0); 334 else ZWRAP_useZSTDcompression(1); 335 do { 336 U32 blockNb; 337 for (blockNb=0; blockNb<nbBlocks; blockNb++) { 338 int ret; 339 def.zalloc = Z_NULL; 340 def.zfree = Z_NULL; 341 def.opaque = Z_NULL; 342 ret = deflateInit(&def, cLevel); 343 if (ret != Z_OK) EXM_THROW(1, "deflateInit failure"); 344 if (dictBuffer) { 345 ret = deflateSetDictionary(&def, dictBuffer, dictBufferSize); 346 if (ret != Z_OK) EXM_THROW(1, "deflateSetDictionary failure"); 347 } 348 def.next_in = (z_const void*) blockTable[blockNb].srcPtr; 349 def.avail_in = (uInt)blockTable[blockNb].srcSize; 350 def.total_in = 0; 351 def.next_out = (void*) blockTable[blockNb].cPtr; 352 def.avail_out = (uInt)blockTable[blockNb].cRoom; 353 def.total_out = 0; 354 ret = deflate(&def, Z_FINISH); 355 if (ret != Z_STREAM_END) EXM_THROW(1, "deflate failure"); 356 ret = deflateEnd(&def); 357 if (ret != Z_OK) EXM_THROW(1, "deflateEnd failure"); 358 blockTable[blockNb].cSize = def.total_out; 359 } 360 nbLoops++; 361 } while (UTIL_clockSpanMicro(clockStart) < clockLoop); 362 } 363 { U64 const clockSpan = UTIL_clockSpanMicro(clockStart); 364 if (clockSpan < fastestC*nbLoops) fastestC = clockSpan / nbLoops; 365 totalCTime += clockSpan; 366 cCompleted = totalCTime>maxTime; 367 } } 368 369 cSize = 0; 370 { U32 blockNb; for (blockNb=0; blockNb<nbBlocks; blockNb++) cSize += blockTable[blockNb].cSize; } 371 ratio = (double)srcSize / (double)cSize; 372 markNb = (markNb+1) % NB_MARKS; 373 DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s\r", 374 marks[markNb], displayName, (unsigned)srcSize, (unsigned)cSize, ratio, 375 (double)srcSize / fastestC ); 376 377 (void)fastestD; (void)crcOrig; /* unused when decompression disabled */ 378 #if 1 379 /* Decompression */ 380 if (!dCompleted) memset(resultBuffer, 0xD6, srcSize); /* warm result buffer */ 381 382 UTIL_sleepMilli(1); /* give processor time to other processes */ 383 UTIL_waitForNextTick(); 384 clockStart = UTIL_getTime(); 385 386 if (!dCompleted) { 387 U32 nbLoops = 0; 388 if (compressor == BMK_ZSTD) { 389 ZSTD_DDict* ddict = ZSTD_createDDict(dictBuffer, dictBufferSize); 390 if (!ddict) EXM_THROW(2, "ZSTD_createDDict() allocation failure"); 391 do { 392 unsigned blockNb; 393 for (blockNb=0; blockNb<nbBlocks; blockNb++) { 394 size_t const regenSize = ZSTD_decompress_usingDDict(dctx, 395 blockTable[blockNb].resPtr, blockTable[blockNb].srcSize, 396 blockTable[blockNb].cPtr, blockTable[blockNb].cSize, 397 ddict); 398 if (ZSTD_isError(regenSize)) { 399 DISPLAY("ZSTD_decompress_usingDDict() failed on block %u : %s \n", 400 blockNb, ZSTD_getErrorName(regenSize)); 401 clockLoop = 0; /* force immediate test end */ 402 break; 403 } 404 blockTable[blockNb].resSize = regenSize; 405 } 406 nbLoops++; 407 } while (UTIL_clockSpanMicro(clockStart) < clockLoop); 408 ZSTD_freeDDict(ddict); 409 } else if (compressor == BMK_ZSTD_STREAM) { 410 ZSTD_inBuffer inBuffer; 411 ZSTD_outBuffer outBuffer; 412 ZSTD_DStream* zbd = ZSTD_createDStream(); 413 size_t rSize; 414 if (zbd == NULL) EXM_THROW(1, "ZSTD_createDStream() allocation failure"); 415 rSize = ZSTD_initDStream_usingDict(zbd, dictBuffer, dictBufferSize); 416 if (ZSTD_isError(rSize)) EXM_THROW(1, "ZSTD_initDStream() failed : %s", ZSTD_getErrorName(rSize)); 417 do { 418 U32 blockNb; 419 for (blockNb=0; blockNb<nbBlocks; blockNb++) { 420 rSize = ZSTD_resetDStream(zbd); 421 if (ZSTD_isError(rSize)) EXM_THROW(1, "ZSTD_resetDStream() failed : %s", ZSTD_getErrorName(rSize)); 422 inBuffer.src = blockTable[blockNb].cPtr; 423 inBuffer.size = blockTable[blockNb].cSize; 424 inBuffer.pos = 0; 425 outBuffer.dst = blockTable[blockNb].resPtr; 426 outBuffer.size = blockTable[blockNb].srcSize; 427 outBuffer.pos = 0; 428 rSize = ZSTD_decompressStream(zbd, &outBuffer, &inBuffer); 429 if (ZSTD_isError(rSize)) EXM_THROW(1, "ZSTD_decompressStream() failed : %s", ZSTD_getErrorName(rSize)); 430 blockTable[blockNb].resSize = outBuffer.pos; 431 } 432 nbLoops++; 433 } while (UTIL_clockSpanMicro(clockStart) < clockLoop); 434 ZSTD_freeDStream(zbd); 435 } else if (compressor == BMK_ZWRAP_ZLIB_REUSE || compressor == BMK_ZWRAP_ZSTD_REUSE || compressor == BMK_ZLIB_REUSE) { 436 z_stream inf; 437 int ret; 438 if (compressor == BMK_ZLIB_REUSE) ZWRAP_setDecompressionType(ZWRAP_FORCE_ZLIB); 439 else ZWRAP_setDecompressionType(ZWRAP_AUTO); 440 inf.zalloc = Z_NULL; 441 inf.zfree = Z_NULL; 442 inf.opaque = Z_NULL; 443 ret = inflateInit(&inf); 444 if (ret != Z_OK) EXM_THROW(1, "inflateInit failure"); 445 do { 446 U32 blockNb; 447 for (blockNb=0; blockNb<nbBlocks; blockNb++) { 448 if (ZWRAP_isUsingZSTDdecompression(&inf)) 449 ret = ZWRAP_inflateReset_keepDict(&inf); /* reuse dictionary to make decompression faster; inflate will return Z_NEED_DICT only for the first time */ 450 else 451 ret = inflateReset(&inf); 452 if (ret != Z_OK) EXM_THROW(1, "inflateReset failure"); 453 inf.next_in = (z_const void*) blockTable[blockNb].cPtr; 454 inf.avail_in = (uInt)blockTable[blockNb].cSize; 455 inf.total_in = 0; 456 inf.next_out = (void*) blockTable[blockNb].resPtr; 457 inf.avail_out = (uInt)blockTable[blockNb].srcSize; 458 inf.total_out = 0; 459 ret = inflate(&inf, Z_FINISH); 460 if (ret == Z_NEED_DICT) { 461 ret = inflateSetDictionary(&inf, dictBuffer, dictBufferSize); 462 if (ret != Z_OK) EXM_THROW(1, "inflateSetDictionary failure"); 463 ret = inflate(&inf, Z_FINISH); 464 } 465 if (ret != Z_STREAM_END) EXM_THROW(1, "inflate failure"); 466 blockTable[blockNb].resSize = inf.total_out; 467 } 468 nbLoops++; 469 } while (UTIL_clockSpanMicro(clockStart) < clockLoop); 470 ret = inflateEnd(&inf); 471 if (ret != Z_OK) EXM_THROW(1, "inflateEnd failure"); 472 } else { 473 z_stream inf; 474 if (compressor == BMK_ZLIB) ZWRAP_setDecompressionType(ZWRAP_FORCE_ZLIB); 475 else ZWRAP_setDecompressionType(ZWRAP_AUTO); 476 do { 477 U32 blockNb; 478 for (blockNb=0; blockNb<nbBlocks; blockNb++) { 479 int ret; 480 inf.zalloc = Z_NULL; 481 inf.zfree = Z_NULL; 482 inf.opaque = Z_NULL; 483 ret = inflateInit(&inf); 484 if (ret != Z_OK) EXM_THROW(1, "inflateInit failure"); 485 inf.next_in = (z_const void*) blockTable[blockNb].cPtr; 486 inf.avail_in = (uInt)blockTable[blockNb].cSize; 487 inf.total_in = 0; 488 inf.next_out = (void*) blockTable[blockNb].resPtr; 489 inf.avail_out = (uInt)blockTable[blockNb].srcSize; 490 inf.total_out = 0; 491 ret = inflate(&inf, Z_FINISH); 492 if (ret == Z_NEED_DICT) { 493 ret = inflateSetDictionary(&inf, dictBuffer, dictBufferSize); 494 if (ret != Z_OK) EXM_THROW(1, "inflateSetDictionary failure"); 495 ret = inflate(&inf, Z_FINISH); 496 } 497 if (ret != Z_STREAM_END) EXM_THROW(1, "inflate failure"); 498 ret = inflateEnd(&inf); 499 if (ret != Z_OK) EXM_THROW(1, "inflateEnd failure"); 500 blockTable[blockNb].resSize = inf.total_out; 501 } 502 nbLoops++; 503 } while (UTIL_clockSpanMicro(clockStart) < clockLoop); 504 } 505 { U64 const clockSpan = UTIL_clockSpanMicro(clockStart); 506 if (clockSpan < fastestD*nbLoops) fastestD = clockSpan / nbLoops; 507 totalDTime += clockSpan; 508 dCompleted = totalDTime>maxTime; 509 } } 510 511 markNb = (markNb+1) % NB_MARKS; 512 DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s ,%6.1f MB/s\r", 513 marks[markNb], displayName, (unsigned)srcSize, (unsigned)cSize, ratio, 514 (double)srcSize / fastestC, 515 (double)srcSize / fastestD ); 516 517 /* CRC Checking */ 518 { U64 const crcCheck = XXH64(resultBuffer, srcSize, 0); 519 if (crcOrig!=crcCheck) { 520 size_t u; 521 DISPLAY("!!! WARNING !!! %14s : Invalid Checksum : %x != %x \n", displayName, (unsigned)crcOrig, (unsigned)crcCheck); 522 for (u=0; u<srcSize; u++) { 523 if (((const BYTE*)srcBuffer)[u] != ((const BYTE*)resultBuffer)[u]) { 524 unsigned segNb, bNb, pos; 525 size_t bacc = 0; 526 DISPLAY("Decoding error at pos %u ", (unsigned)u); 527 for (segNb = 0; segNb < nbBlocks; segNb++) { 528 if (bacc + blockTable[segNb].srcSize > u) break; 529 bacc += blockTable[segNb].srcSize; 530 } 531 pos = (U32)(u - bacc); 532 bNb = pos / (128 KB); 533 DISPLAY("(block %u, sub %u, pos %u) \n", segNb, bNb, pos); 534 break; 535 } 536 if (u==srcSize-1) { /* should never happen */ 537 DISPLAY("no difference detected\n"); 538 } } 539 break; 540 } } /* CRC Checking */ 541 #endif 542 } /* for (testNb = 1; testNb <= (g_nbIterations + !g_nbIterations); testNb++) */ 543 544 if (g_displayLevel == 1) { 545 double cSpeed = (double)srcSize / fastestC; 546 double dSpeed = (double)srcSize / fastestD; 547 if (g_additionalParam) 548 DISPLAY("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s %s (param=%d)\n", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName, g_additionalParam); 549 else 550 DISPLAY("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s %s\n", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName); 551 } 552 DISPLAYLEVEL(2, "%2i#\n", cLevel); 553 } /* Bench */ 554 555 /* clean up */ 556 free(blockTable); 557 free(compressedBuffer); 558 free(resultBuffer); 559 ZSTD_freeCCtx(ctx); 560 ZSTD_freeDCtx(dctx); 561 return 0; 562 } 563 564 565 static size_t BMK_findMaxMem(U64 requiredMem) 566 { 567 size_t const step = 64 MB; 568 BYTE* testmem = NULL; 569 570 requiredMem = (((requiredMem >> 26) + 1) << 26); 571 requiredMem += step; 572 if (requiredMem > maxMemory) requiredMem = maxMemory; 573 574 do { 575 testmem = (BYTE*)malloc((size_t)requiredMem); 576 requiredMem -= step; 577 } while (!testmem && requiredMem); /* do not allocate zero bytes */ 578 579 free(testmem); 580 return (size_t)(requiredMem+1); /* avoid zero */ 581 } 582 583 static void BMK_benchCLevel(void* srcBuffer, size_t benchedSize, 584 const char* displayName, int cLevel, int cLevelLast, 585 const size_t* fileSizes, unsigned nbFiles, 586 const void* dictBuffer, size_t dictBufferSize) 587 { 588 int l; 589 590 const char* pch = strrchr(displayName, '\\'); /* Windows */ 591 if (!pch) pch = strrchr(displayName, '/'); /* Linux */ 592 if (pch) displayName = pch+1; 593 594 SET_REALTIME_PRIORITY; 595 596 if (g_displayLevel == 1 && !g_additionalParam) 597 DISPLAY("bench %s %s: input %u bytes, %u seconds, %u KB blocks\n", 598 ZSTD_VERSION_STRING, ZSTD_GIT_COMMIT_STRING, 599 (unsigned)benchedSize, g_nbIterations, (unsigned)(g_blockSize>>10)); 600 601 if (cLevelLast < cLevel) cLevelLast = cLevel; 602 603 DISPLAY("benchmarking zstd %s (using ZSTD_CStream)\n", ZSTD_VERSION_STRING); 604 for (l=cLevel; l <= cLevelLast; l++) { 605 BMK_benchMem(srcBuffer, benchedSize, 606 displayName, l, 607 fileSizes, nbFiles, 608 dictBuffer, dictBufferSize, BMK_ZSTD_STREAM); 609 } 610 611 DISPLAY("benchmarking zstd %s (using ZSTD_CCtx)\n", ZSTD_VERSION_STRING); 612 for (l=cLevel; l <= cLevelLast; l++) { 613 BMK_benchMem(srcBuffer, benchedSize, 614 displayName, l, 615 fileSizes, nbFiles, 616 dictBuffer, dictBufferSize, BMK_ZSTD); 617 } 618 619 DISPLAY("benchmarking zstd %s (using zlibWrapper)\n", ZSTD_VERSION_STRING); 620 for (l=cLevel; l <= cLevelLast; l++) { 621 BMK_benchMem(srcBuffer, benchedSize, 622 displayName, l, 623 fileSizes, nbFiles, 624 dictBuffer, dictBufferSize, BMK_ZWRAP_ZSTD_REUSE); 625 } 626 627 DISPLAY("benchmarking zstd %s (zlibWrapper not reusing a context)\n", ZSTD_VERSION_STRING); 628 for (l=cLevel; l <= cLevelLast; l++) { 629 BMK_benchMem(srcBuffer, benchedSize, 630 displayName, l, 631 fileSizes, nbFiles, 632 dictBuffer, dictBufferSize, BMK_ZWRAP_ZSTD); 633 } 634 635 636 if (cLevelLast > Z_BEST_COMPRESSION) cLevelLast = Z_BEST_COMPRESSION; 637 638 DISPLAY("\n"); 639 DISPLAY("benchmarking zlib %s\n", ZLIB_VERSION); 640 for (l=cLevel; l <= cLevelLast; l++) { 641 BMK_benchMem(srcBuffer, benchedSize, 642 displayName, l, 643 fileSizes, nbFiles, 644 dictBuffer, dictBufferSize, BMK_ZLIB_REUSE); 645 } 646 647 DISPLAY("benchmarking zlib %s (zlib not reusing a context)\n", ZLIB_VERSION); 648 for (l=cLevel; l <= cLevelLast; l++) { 649 BMK_benchMem(srcBuffer, benchedSize, 650 displayName, l, 651 fileSizes, nbFiles, 652 dictBuffer, dictBufferSize, BMK_ZLIB); 653 } 654 655 DISPLAY("benchmarking zlib %s (using zlibWrapper)\n", ZLIB_VERSION); 656 for (l=cLevel; l <= cLevelLast; l++) { 657 BMK_benchMem(srcBuffer, benchedSize, 658 displayName, l, 659 fileSizes, nbFiles, 660 dictBuffer, dictBufferSize, BMK_ZWRAP_ZLIB_REUSE); 661 } 662 663 DISPLAY("benchmarking zlib %s (zlibWrapper not reusing a context)\n", ZLIB_VERSION); 664 for (l=cLevel; l <= cLevelLast; l++) { 665 BMK_benchMem(srcBuffer, benchedSize, 666 displayName, l, 667 fileSizes, nbFiles, 668 dictBuffer, dictBufferSize, BMK_ZWRAP_ZLIB); 669 } 670 } 671 672 673 /*! BMK_loadFiles() : 674 Loads `buffer` with content of files listed within `fileNamesTable`. 675 At most, fills `buffer` entirely */ 676 static void BMK_loadFiles(void* buffer, size_t bufferSize, 677 size_t* fileSizes, 678 const char** fileNamesTable, unsigned nbFiles) 679 { 680 size_t pos = 0, totalSize = 0; 681 unsigned n; 682 for (n=0; n<nbFiles; n++) { 683 FILE* f; 684 U64 fileSize = UTIL_getFileSize(fileNamesTable[n]); 685 if (UTIL_isDirectory(fileNamesTable[n])) { 686 DISPLAYLEVEL(2, "Ignoring %s directory... \n", fileNamesTable[n]); 687 fileSizes[n] = 0; 688 continue; 689 } 690 if (fileSize == UTIL_FILESIZE_UNKNOWN) { 691 DISPLAYLEVEL(2, "Cannot determine size of %s ... \n", fileNamesTable[n]); 692 fileSizes[n] = 0; 693 continue; 694 } 695 f = fopen(fileNamesTable[n], "rb"); 696 if (f==NULL) EXM_THROW(10, "impossible to open file %s", fileNamesTable[n]); 697 DISPLAYUPDATE(2, "Loading %s... \r", fileNamesTable[n]); 698 if (fileSize > bufferSize-pos) fileSize = bufferSize-pos, nbFiles=n; /* buffer too small - stop after this file */ 699 { size_t const readSize = fread(((char*)buffer)+pos, 1, (size_t)fileSize, f); 700 if (readSize != (size_t)fileSize) EXM_THROW(11, "could not read %s", fileNamesTable[n]); 701 pos += readSize; } 702 fileSizes[n] = (size_t)fileSize; 703 totalSize += (size_t)fileSize; 704 fclose(f); 705 } 706 707 if (totalSize == 0) EXM_THROW(12, "no data to bench"); 708 } 709 710 static void BMK_benchFileTable(const char** fileNamesTable, unsigned nbFiles, 711 const char* dictFileName, int cLevel, int cLevelLast) 712 { 713 void* srcBuffer; 714 size_t benchedSize; 715 void* dictBuffer = NULL; 716 size_t dictBufferSize = 0; 717 size_t* fileSizes = (size_t*)malloc(nbFiles * sizeof(size_t)); 718 U64 const totalSizeToLoad = UTIL_getTotalFileSize(fileNamesTable, nbFiles); 719 char mfName[20] = {0}; 720 721 if (!fileSizes) EXM_THROW(12, "not enough memory for fileSizes"); 722 723 /* Load dictionary */ 724 if (dictFileName != NULL) { 725 U64 const dictFileSize = UTIL_getFileSize(dictFileName); 726 if (dictFileSize > 64 MB) 727 EXM_THROW(10, "dictionary file %s too large", dictFileName); 728 dictBufferSize = (size_t)dictFileSize; 729 dictBuffer = malloc(dictBufferSize); 730 if (dictBuffer==NULL) 731 EXM_THROW(11, "not enough memory for dictionary (%u bytes)", (unsigned)dictBufferSize); 732 BMK_loadFiles(dictBuffer, dictBufferSize, fileSizes, &dictFileName, 1); 733 } 734 735 /* Memory allocation & restrictions */ 736 benchedSize = BMK_findMaxMem(totalSizeToLoad * 3) / 3; 737 if ((U64)benchedSize > totalSizeToLoad) benchedSize = (size_t)totalSizeToLoad; 738 if (benchedSize < totalSizeToLoad) 739 DISPLAY("Not enough memory; testing %u MB only...\n", (unsigned)(benchedSize >> 20)); 740 srcBuffer = malloc(benchedSize + !benchedSize); 741 if (!srcBuffer) EXM_THROW(12, "not enough memory"); 742 743 /* Load input buffer */ 744 BMK_loadFiles(srcBuffer, benchedSize, fileSizes, fileNamesTable, nbFiles); 745 746 /* Bench */ 747 snprintf (mfName, sizeof(mfName), " %u files", nbFiles); 748 { const char* displayName = (nbFiles > 1) ? mfName : fileNamesTable[0]; 749 BMK_benchCLevel(srcBuffer, benchedSize, 750 displayName, cLevel, cLevelLast, 751 fileSizes, nbFiles, 752 dictBuffer, dictBufferSize); 753 } 754 755 /* clean up */ 756 free(srcBuffer); 757 free(dictBuffer); 758 free(fileSizes); 759 } 760 761 762 static void BMK_syntheticTest(int cLevel, int cLevelLast, double compressibility) 763 { 764 char name[20] = {0}; 765 size_t benchedSize = 10000000; 766 void* const srcBuffer = malloc(benchedSize); 767 768 /* Memory allocation */ 769 if (!srcBuffer) EXM_THROW(21, "not enough memory"); 770 771 /* Fill input buffer */ 772 RDG_genBuffer(srcBuffer, benchedSize, compressibility, 0.0, 0); 773 774 /* Bench */ 775 snprintf (name, sizeof(name), "Synthetic %2u%%", (unsigned)(compressibility*100)); 776 BMK_benchCLevel(srcBuffer, benchedSize, name, cLevel, cLevelLast, &benchedSize, 1, NULL, 0); 777 778 /* clean up */ 779 free(srcBuffer); 780 } 781 782 783 int BMK_benchFiles(const char** fileNamesTable, unsigned nbFiles, 784 const char* dictFileName, int cLevel, int cLevelLast) 785 { 786 double const compressibility = (double)g_compressibilityDefault / 100; 787 788 if (nbFiles == 0) 789 BMK_syntheticTest(cLevel, cLevelLast, compressibility); 790 else 791 BMK_benchFileTable(fileNamesTable, nbFiles, dictFileName, cLevel, cLevelLast); 792 return 0; 793 } 794 795 796 797 798 /*-************************************ 799 * Command Line 800 **************************************/ 801 static int usage(const char* programName) 802 { 803 DISPLAY(WELCOME_MESSAGE); 804 DISPLAY( "Usage :\n"); 805 DISPLAY( " %s [args] [FILE(s)] [-o file]\n", programName); 806 DISPLAY( "\n"); 807 DISPLAY( "FILE : a filename\n"); 808 DISPLAY( " with no FILE, or when FILE is - , read standard input\n"); 809 DISPLAY( "Arguments :\n"); 810 DISPLAY( " -D file: use `file` as Dictionary \n"); 811 DISPLAY( " -h/-H : display help/long help and exit\n"); 812 DISPLAY( " -V : display Version number and exit\n"); 813 DISPLAY( " -v : verbose mode; specify multiple times to increase log level (default:%d)\n", DEFAULT_DISPLAY_LEVEL); 814 DISPLAY( " -q : suppress warnings; specify twice to suppress errors too\n"); 815 #ifdef UTIL_HAS_CREATEFILELIST 816 DISPLAY( " -r : operate recursively on directories\n"); 817 #endif 818 DISPLAY( "\n"); 819 DISPLAY( "Benchmark arguments :\n"); 820 DISPLAY( " -b# : benchmark file(s), using # compression level (default : %d) \n", ZSTDCLI_CLEVEL_DEFAULT); 821 DISPLAY( " -e# : test all compression levels from -bX to # (default: %d)\n", ZSTDCLI_CLEVEL_DEFAULT); 822 DISPLAY( " -i# : minimum evaluation time in seconds (default : 3s)\n"); 823 DISPLAY( " -B# : cut file into independent blocks of size # (default: no block)\n"); 824 return 0; 825 } 826 827 static int badusage(const char* programName) 828 { 829 DISPLAYLEVEL(1, "Incorrect parameters\n"); 830 if (g_displayLevel >= 1) usage(programName); 831 return 1; 832 } 833 834 static void waitEnter(void) 835 { 836 int unused; 837 DISPLAY("Press enter to continue...\n"); 838 unused = getchar(); 839 (void)unused; 840 } 841 842 /*! readU32FromChar() : 843 @return : unsigned integer value reach from input in `char` format 844 Will also modify `*stringPtr`, advancing it to position where it stopped reading. 845 Note : this function can overflow if digit string > MAX_UINT */ 846 static unsigned readU32FromChar(const char** stringPtr) 847 { 848 unsigned result = 0; 849 while ((**stringPtr >='0') && (**stringPtr <='9')) 850 result *= 10, result += **stringPtr - '0', (*stringPtr)++ ; 851 return result; 852 } 853 854 855 #define CLEAN_RETURN(i) { operationResult = (i); goto _end; } 856 857 int main(int argCount, char** argv) 858 { 859 int argNb, 860 main_pause=0, 861 nextEntryIsDictionary=0, 862 operationResult=0, 863 nextArgumentIsFile=0; 864 int cLevel = ZSTDCLI_CLEVEL_DEFAULT; 865 int cLevelLast = 1; 866 unsigned recursive = 0; 867 const char** filenameTable = (const char**)malloc(argCount * sizeof(const char*)); /* argCount >= 1 */ 868 unsigned filenameIdx = 0; 869 const char* programName = argv[0]; 870 const char* dictFileName = NULL; 871 char* dynNameSpace = NULL; 872 #ifdef UTIL_HAS_CREATEFILELIST 873 const char** fileNamesTable = NULL; 874 char* fileNamesBuf = NULL; 875 unsigned fileNamesNb; 876 #endif 877 878 /* init */ 879 if (filenameTable==NULL) { DISPLAY("zstd: %s \n", strerror(errno)); exit(1); } 880 displayOut = stderr; 881 882 /* Pick out program name from path. Don't rely on stdlib because of conflicting behavior */ 883 { size_t pos; 884 for (pos = (int)strlen(programName); pos > 0; pos--) { if (programName[pos] == '/') { pos++; break; } } 885 programName += pos; 886 } 887 888 /* command switches */ 889 for(argNb=1; argNb<argCount; argNb++) { 890 const char* argument = argv[argNb]; 891 if(!argument) continue; /* Protection if argument empty */ 892 893 if (nextArgumentIsFile==0) { 894 895 /* long commands (--long-word) */ 896 if (!strcmp(argument, "--")) { nextArgumentIsFile=1; continue; } 897 if (!strcmp(argument, "--version")) { displayOut=stdout; DISPLAY(WELCOME_MESSAGE); CLEAN_RETURN(0); } 898 if (!strcmp(argument, "--help")) { displayOut=stdout; CLEAN_RETURN(usage(programName)); } 899 if (!strcmp(argument, "--verbose")) { g_displayLevel++; continue; } 900 if (!strcmp(argument, "--quiet")) { g_displayLevel--; continue; } 901 902 /* Decode commands (note : aggregated commands are allowed) */ 903 if (argument[0]=='-') { 904 argument++; 905 906 while (argument[0]!=0) { 907 switch(argument[0]) 908 { 909 /* Display help */ 910 case 'V': displayOut=stdout; DISPLAY(WELCOME_MESSAGE); CLEAN_RETURN(0); /* Version Only */ 911 case 'H': 912 case 'h': displayOut=stdout; CLEAN_RETURN(usage(programName)); 913 914 /* Use file content as dictionary */ 915 case 'D': nextEntryIsDictionary = 1; argument++; break; 916 917 /* Verbose mode */ 918 case 'v': g_displayLevel++; argument++; break; 919 920 /* Quiet mode */ 921 case 'q': g_displayLevel--; argument++; break; 922 923 #ifdef UTIL_HAS_CREATEFILELIST 924 /* recursive */ 925 case 'r': recursive=1; argument++; break; 926 #endif 927 928 /* Benchmark */ 929 case 'b': 930 /* first compression Level */ 931 argument++; 932 cLevel = readU32FromChar(&argument); 933 break; 934 935 /* range bench (benchmark only) */ 936 case 'e': 937 /* last compression Level */ 938 argument++; 939 cLevelLast = readU32FromChar(&argument); 940 break; 941 942 /* Modify Nb Iterations (benchmark only) */ 943 case 'i': 944 argument++; 945 { U32 const iters = readU32FromChar(&argument); 946 BMK_setNotificationLevel(g_displayLevel); 947 BMK_SetNbIterations(iters); 948 } 949 break; 950 951 /* cut input into blocks (benchmark only) */ 952 case 'B': 953 argument++; 954 { size_t bSize = readU32FromChar(&argument); 955 if (toupper(*argument)=='K') bSize<<=10, argument++; /* allows using KB notation */ 956 if (toupper(*argument)=='M') bSize<<=20, argument++; 957 if (toupper(*argument)=='B') argument++; 958 BMK_setNotificationLevel(g_displayLevel); 959 BMK_SetBlockSize(bSize); 960 } 961 break; 962 963 /* Pause at the end (-p) or set an additional param (-p#) (hidden option) */ 964 case 'p': argument++; 965 if ((*argument>='0') && (*argument<='9')) { 966 BMK_setAdditionalParam(readU32FromChar(&argument)); 967 } else 968 main_pause=1; 969 break; 970 /* unknown command */ 971 default : CLEAN_RETURN(badusage(programName)); 972 } 973 } 974 continue; 975 } /* if (argument[0]=='-') */ 976 977 } /* if (nextArgumentIsAFile==0) */ 978 979 if (nextEntryIsDictionary) { 980 nextEntryIsDictionary = 0; 981 dictFileName = argument; 982 continue; 983 } 984 985 /* add filename to list */ 986 filenameTable[filenameIdx++] = argument; 987 } 988 989 /* Welcome message (if verbose) */ 990 DISPLAYLEVEL(3, WELCOME_MESSAGE); 991 992 #ifdef UTIL_HAS_CREATEFILELIST 993 if (recursive) { 994 fileNamesTable = UTIL_createFileList(filenameTable, filenameIdx, &fileNamesBuf, &fileNamesNb, 1); 995 if (fileNamesTable) { 996 unsigned u; 997 for (u=0; u<fileNamesNb; u++) DISPLAYLEVEL(4, "%u %s\n", u, fileNamesTable[u]); 998 free((void*)filenameTable); 999 filenameTable = fileNamesTable; 1000 filenameIdx = fileNamesNb; 1001 } 1002 } 1003 #endif 1004 1005 BMK_setNotificationLevel(g_displayLevel); 1006 BMK_benchFiles(filenameTable, filenameIdx, dictFileName, cLevel, cLevelLast); 1007 1008 _end: 1009 if (main_pause) waitEnter(); 1010 free(dynNameSpace); 1011 #ifdef UTIL_HAS_CREATEFILELIST 1012 if (fileNamesTable) 1013 UTIL_freeFileList(fileNamesTable, fileNamesBuf); 1014 else 1015 #endif 1016 free((void*)filenameTable); 1017 return operationResult; 1018 } 1019