benchzstd.c 36 KB

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