Path: blob/main/sys/contrib/zstd/programs/benchzstd.c
48254 views
/*1* Copyright (c) Yann Collet, Facebook, Inc.2* All rights reserved.3*4* This source code is licensed under both the BSD-style license (found in the5* LICENSE file in the root directory of this source tree) and the GPLv2 (found6* in the COPYING file in the root directory of this source tree).7* You may select, at your option, one of the above-listed licenses.8*/91011/* **************************************12* Tuning parameters13****************************************/14#ifndef BMK_TIMETEST_DEFAULT_S /* default minimum time per test */15#define BMK_TIMETEST_DEFAULT_S 316#endif171819/* *************************************20* Includes21***************************************/22#include "platform.h" /* Large Files support */23#include "util.h" /* UTIL_getFileSize, UTIL_sleep */24#include <stdlib.h> /* malloc, free */25#include <string.h> /* memset, strerror */26#include <stdio.h> /* fprintf, fopen */27#include <errno.h>28#include <assert.h> /* assert */2930#include "timefn.h" /* UTIL_time_t */31#include "benchfn.h"32#include "../lib/common/mem.h"33#ifndef ZSTD_STATIC_LINKING_ONLY34#define ZSTD_STATIC_LINKING_ONLY35#endif36#include "../lib/zstd.h"37#include "datagen.h" /* RDG_genBuffer */38#ifndef XXH_INLINE_ALL39#define XXH_INLINE_ALL40#endif41#include "../lib/common/xxhash.h"42#include "benchzstd.h"43#include "../lib/zstd_errors.h"444546/* *************************************47* Constants48***************************************/49#ifndef ZSTD_GIT_COMMIT50# define ZSTD_GIT_COMMIT_STRING ""51#else52# define ZSTD_GIT_COMMIT_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_GIT_COMMIT)53#endif5455#define TIMELOOP_MICROSEC (1*1000000ULL) /* 1 second */56#define TIMELOOP_NANOSEC (1*1000000000ULL) /* 1 second */57#define ACTIVEPERIOD_MICROSEC (70*TIMELOOP_MICROSEC) /* 70 seconds */58#define COOLPERIOD_SEC 105960#define KB *(1 <<10)61#define MB *(1 <<20)62#define GB *(1U<<30)6364#define BMK_RUNTEST_DEFAULT_MS 10006566static const size_t maxMemory = (sizeof(size_t)==4) ?67/* 32-bit */ (2 GB - 64 MB) :68/* 64-bit */ (size_t)(1ULL << ((sizeof(size_t)*8)-31));697071/* *************************************72* console display73***************************************/74#define DISPLAY(...) { fprintf(stderr, __VA_ARGS__); fflush(NULL); }75#define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }76/* 0 : no display; 1: errors; 2 : + result + interaction + warnings; 3 : + progression; 4 : + information */77#define OUTPUT(...) { fprintf(stdout, __VA_ARGS__); fflush(NULL); }78#define OUTPUTLEVEL(l, ...) if (displayLevel>=l) { OUTPUT(__VA_ARGS__); }798081/* *************************************82* Exceptions83***************************************/84#ifndef DEBUG85# define DEBUG 086#endif87#define DEBUGOUTPUT(...) { if (DEBUG) DISPLAY(__VA_ARGS__); }8889#define RETURN_ERROR_INT(errorNum, ...) { \90DEBUGOUTPUT("%s: %i: \n", __FILE__, __LINE__); \91DISPLAYLEVEL(1, "Error %i : ", errorNum); \92DISPLAYLEVEL(1, __VA_ARGS__); \93DISPLAYLEVEL(1, " \n"); \94return errorNum; \95}9697#define CHECK_Z(zf) { \98size_t const zerr = zf; \99if (ZSTD_isError(zerr)) { \100DEBUGOUTPUT("%s: %i: \n", __FILE__, __LINE__); \101DISPLAY("Error : "); \102DISPLAY("%s failed : %s", \103#zf, ZSTD_getErrorName(zerr)); \104DISPLAY(" \n"); \105exit(1); \106} \107}108109#define RETURN_ERROR(errorNum, retType, ...) { \110retType r; \111memset(&r, 0, sizeof(retType)); \112DEBUGOUTPUT("%s: %i: \n", __FILE__, __LINE__); \113DISPLAYLEVEL(1, "Error %i : ", errorNum); \114DISPLAYLEVEL(1, __VA_ARGS__); \115DISPLAYLEVEL(1, " \n"); \116r.tag = errorNum; \117return r; \118}119120121/* *************************************122* Benchmark Parameters123***************************************/124125BMK_advancedParams_t BMK_initAdvancedParams(void) {126BMK_advancedParams_t const res = {127BMK_both, /* mode */128BMK_TIMETEST_DEFAULT_S, /* nbSeconds */1290, /* blockSize */1300, /* nbWorkers */1310, /* realTime */1320, /* additionalParam */1330, /* ldmFlag */1340, /* ldmMinMatch */1350, /* ldmHashLog */1360, /* ldmBuckSizeLog */1370, /* ldmHashRateLog */138ZSTD_ps_auto, /* literalCompressionMode */1390 /* useRowMatchFinder */140};141return res;142}143144145/* ********************************************************146* Bench functions147**********************************************************/148typedef struct {149const void* srcPtr;150size_t srcSize;151void* cPtr;152size_t cRoom;153size_t cSize;154void* resPtr;155size_t resSize;156} blockParam_t;157158#undef MIN159#undef MAX160#define MIN(a,b) ((a) < (b) ? (a) : (b))161#define MAX(a,b) ((a) > (b) ? (a) : (b))162163static void164BMK_initCCtx(ZSTD_CCtx* ctx,165const void* dictBuffer, size_t dictBufferSize,166int cLevel,167const ZSTD_compressionParameters* comprParams,168const BMK_advancedParams_t* adv)169{170ZSTD_CCtx_reset(ctx, ZSTD_reset_session_and_parameters);171if (adv->nbWorkers==1) {172CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_nbWorkers, 0));173} else {174CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_nbWorkers, adv->nbWorkers));175}176CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_compressionLevel, cLevel));177CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_useRowMatchFinder, adv->useRowMatchFinder));178CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_enableLongDistanceMatching, adv->ldmFlag));179CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_ldmMinMatch, adv->ldmMinMatch));180CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_ldmHashLog, adv->ldmHashLog));181CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_ldmBucketSizeLog, adv->ldmBucketSizeLog));182CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_ldmHashRateLog, adv->ldmHashRateLog));183CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_windowLog, (int)comprParams->windowLog));184CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_hashLog, (int)comprParams->hashLog));185CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_chainLog, (int)comprParams->chainLog));186CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_searchLog, (int)comprParams->searchLog));187CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_minMatch, (int)comprParams->minMatch));188CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_targetLength, (int)comprParams->targetLength));189CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_literalCompressionMode, (int)adv->literalCompressionMode));190CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_strategy, (int)comprParams->strategy));191CHECK_Z(ZSTD_CCtx_loadDictionary(ctx, dictBuffer, dictBufferSize));192}193194static void BMK_initDCtx(ZSTD_DCtx* dctx,195const void* dictBuffer, size_t dictBufferSize) {196CHECK_Z(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters));197CHECK_Z(ZSTD_DCtx_loadDictionary(dctx, dictBuffer, dictBufferSize));198}199200201typedef struct {202ZSTD_CCtx* cctx;203const void* dictBuffer;204size_t dictBufferSize;205int cLevel;206const ZSTD_compressionParameters* comprParams;207const BMK_advancedParams_t* adv;208} BMK_initCCtxArgs;209210static size_t local_initCCtx(void* payload) {211BMK_initCCtxArgs* ag = (BMK_initCCtxArgs*)payload;212BMK_initCCtx(ag->cctx, ag->dictBuffer, ag->dictBufferSize, ag->cLevel, ag->comprParams, ag->adv);213return 0;214}215216typedef struct {217ZSTD_DCtx* dctx;218const void* dictBuffer;219size_t dictBufferSize;220} BMK_initDCtxArgs;221222static size_t local_initDCtx(void* payload) {223BMK_initDCtxArgs* ag = (BMK_initDCtxArgs*)payload;224BMK_initDCtx(ag->dctx, ag->dictBuffer, ag->dictBufferSize);225return 0;226}227228229/* `addArgs` is the context */230static size_t local_defaultCompress(231const void* srcBuffer, size_t srcSize,232void* dstBuffer, size_t dstSize,233void* addArgs)234{235ZSTD_CCtx* const cctx = (ZSTD_CCtx*)addArgs;236return ZSTD_compress2(cctx, dstBuffer, dstSize, srcBuffer, srcSize);237}238239/* `addArgs` is the context */240static size_t local_defaultDecompress(241const void* srcBuffer, size_t srcSize,242void* dstBuffer, size_t dstCapacity,243void* addArgs)244{245size_t moreToFlush = 1;246ZSTD_DCtx* const dctx = (ZSTD_DCtx*)addArgs;247ZSTD_inBuffer in;248ZSTD_outBuffer out;249in.src = srcBuffer; in.size = srcSize; in.pos = 0;250out.dst = dstBuffer; out.size = dstCapacity; out.pos = 0;251while (moreToFlush) {252if(out.pos == out.size) {253return (size_t)-ZSTD_error_dstSize_tooSmall;254}255moreToFlush = ZSTD_decompressStream(dctx, &out, &in);256if (ZSTD_isError(moreToFlush)) {257return moreToFlush;258}259}260return out.pos;261262}263264265/* ================================================================= */266/* Benchmark Zstandard, mem-to-mem scenarios */267/* ================================================================= */268269int BMK_isSuccessful_benchOutcome(BMK_benchOutcome_t outcome)270{271return outcome.tag == 0;272}273274BMK_benchResult_t BMK_extract_benchResult(BMK_benchOutcome_t outcome)275{276assert(outcome.tag == 0);277return outcome.internal_never_use_directly;278}279280static BMK_benchOutcome_t BMK_benchOutcome_error(void)281{282BMK_benchOutcome_t b;283memset(&b, 0, sizeof(b));284b.tag = 1;285return b;286}287288static BMK_benchOutcome_t BMK_benchOutcome_setValidResult(BMK_benchResult_t result)289{290BMK_benchOutcome_t b;291b.tag = 0;292b.internal_never_use_directly = result;293return b;294}295296297/* benchMem with no allocation */298static BMK_benchOutcome_t299BMK_benchMemAdvancedNoAlloc(300const void** srcPtrs, size_t* srcSizes,301void** cPtrs, size_t* cCapacities, size_t* cSizes,302void** resPtrs, size_t* resSizes,303void** resultBufferPtr, void* compressedBuffer,304size_t maxCompressedSize,305BMK_timedFnState_t* timeStateCompress,306BMK_timedFnState_t* timeStateDecompress,307308const void* srcBuffer, size_t srcSize,309const size_t* fileSizes, unsigned nbFiles,310const int cLevel,311const ZSTD_compressionParameters* comprParams,312const void* dictBuffer, size_t dictBufferSize,313ZSTD_CCtx* cctx, ZSTD_DCtx* dctx,314int displayLevel, const char* displayName,315const BMK_advancedParams_t* adv)316{317size_t const blockSize = ((adv->blockSize>=32 && (adv->mode != BMK_decodeOnly)) ? adv->blockSize : srcSize) + (!srcSize); /* avoid div by 0 */318BMK_benchResult_t benchResult;319size_t const loadedCompressedSize = srcSize;320size_t cSize = 0;321double ratio = 0.;322U32 nbBlocks;323324assert(cctx != NULL); assert(dctx != NULL);325326/* init */327memset(&benchResult, 0, sizeof(benchResult));328if (strlen(displayName)>17) displayName += strlen(displayName) - 17; /* display last 17 characters */329if (adv->mode == BMK_decodeOnly) { /* benchmark only decompression : source must be already compressed */330const char* srcPtr = (const char*)srcBuffer;331U64 totalDSize64 = 0;332U32 fileNb;333for (fileNb=0; fileNb<nbFiles; fileNb++) {334U64 const fSize64 = ZSTD_findDecompressedSize(srcPtr, fileSizes[fileNb]);335if (fSize64==0) RETURN_ERROR(32, BMK_benchOutcome_t, "Impossible to determine original size ");336totalDSize64 += fSize64;337srcPtr += fileSizes[fileNb];338}339{ size_t const decodedSize = (size_t)totalDSize64;340assert((U64)decodedSize == totalDSize64); /* check overflow */341free(*resultBufferPtr);342*resultBufferPtr = malloc(decodedSize);343if (!(*resultBufferPtr)) {344RETURN_ERROR(33, BMK_benchOutcome_t, "not enough memory");345}346if (totalDSize64 > decodedSize) { /* size_t overflow */347free(*resultBufferPtr);348RETURN_ERROR(32, BMK_benchOutcome_t, "original size is too large");349}350cSize = srcSize;351srcSize = decodedSize;352ratio = (double)srcSize / (double)cSize;353}354}355356/* Init data blocks */357{ const char* srcPtr = (const char*)srcBuffer;358char* cPtr = (char*)compressedBuffer;359char* resPtr = (char*)(*resultBufferPtr);360U32 fileNb;361for (nbBlocks=0, fileNb=0; fileNb<nbFiles; fileNb++) {362size_t remaining = fileSizes[fileNb];363U32 const nbBlocksforThisFile = (adv->mode == BMK_decodeOnly) ? 1 : (U32)((remaining + (blockSize-1)) / blockSize);364U32 const blockEnd = nbBlocks + nbBlocksforThisFile;365for ( ; nbBlocks<blockEnd; nbBlocks++) {366size_t const thisBlockSize = MIN(remaining, blockSize);367srcPtrs[nbBlocks] = srcPtr;368srcSizes[nbBlocks] = thisBlockSize;369cPtrs[nbBlocks] = cPtr;370cCapacities[nbBlocks] = (adv->mode == BMK_decodeOnly) ? thisBlockSize : ZSTD_compressBound(thisBlockSize);371resPtrs[nbBlocks] = resPtr;372resSizes[nbBlocks] = (adv->mode == BMK_decodeOnly) ? (size_t) ZSTD_findDecompressedSize(srcPtr, thisBlockSize) : thisBlockSize;373srcPtr += thisBlockSize;374cPtr += cCapacities[nbBlocks];375resPtr += thisBlockSize;376remaining -= thisBlockSize;377if (adv->mode == BMK_decodeOnly) {378cSizes[nbBlocks] = thisBlockSize;379benchResult.cSize = thisBlockSize;380} } } }381382/* warming up `compressedBuffer` */383if (adv->mode == BMK_decodeOnly) {384memcpy(compressedBuffer, srcBuffer, loadedCompressedSize);385} else {386RDG_genBuffer(compressedBuffer, maxCompressedSize, 0.10, 0.50, 1);387}388389/* Bench */390{ U64 const crcOrig = (adv->mode == BMK_decodeOnly) ? 0 : XXH64(srcBuffer, srcSize, 0);391# define NB_MARKS 4392const char* marks[NB_MARKS] = { " |", " /", " =", " \\" };393U32 markNb = 0;394int compressionCompleted = (adv->mode == BMK_decodeOnly);395int decompressionCompleted = (adv->mode == BMK_compressOnly);396BMK_benchParams_t cbp, dbp;397BMK_initCCtxArgs cctxprep;398BMK_initDCtxArgs dctxprep;399400cbp.benchFn = local_defaultCompress; /* ZSTD_compress2 */401cbp.benchPayload = cctx;402cbp.initFn = local_initCCtx; /* BMK_initCCtx */403cbp.initPayload = &cctxprep;404cbp.errorFn = ZSTD_isError;405cbp.blockCount = nbBlocks;406cbp.srcBuffers = srcPtrs;407cbp.srcSizes = srcSizes;408cbp.dstBuffers = cPtrs;409cbp.dstCapacities = cCapacities;410cbp.blockResults = cSizes;411412cctxprep.cctx = cctx;413cctxprep.dictBuffer = dictBuffer;414cctxprep.dictBufferSize = dictBufferSize;415cctxprep.cLevel = cLevel;416cctxprep.comprParams = comprParams;417cctxprep.adv = adv;418419dbp.benchFn = local_defaultDecompress;420dbp.benchPayload = dctx;421dbp.initFn = local_initDCtx;422dbp.initPayload = &dctxprep;423dbp.errorFn = ZSTD_isError;424dbp.blockCount = nbBlocks;425dbp.srcBuffers = (const void* const *) cPtrs;426dbp.srcSizes = cSizes;427dbp.dstBuffers = resPtrs;428dbp.dstCapacities = resSizes;429dbp.blockResults = NULL;430431dctxprep.dctx = dctx;432dctxprep.dictBuffer = dictBuffer;433dctxprep.dictBufferSize = dictBufferSize;434435OUTPUTLEVEL(2, "\r%70s\r", ""); /* blank line */436assert(srcSize < UINT_MAX);437OUTPUTLEVEL(2, "%2s-%-17.17s :%10u -> \r", marks[markNb], displayName, (unsigned)srcSize);438439while (!(compressionCompleted && decompressionCompleted)) {440if (!compressionCompleted) {441BMK_runOutcome_t const cOutcome = BMK_benchTimedFn( timeStateCompress, cbp);442443if (!BMK_isSuccessful_runOutcome(cOutcome)) {444return BMK_benchOutcome_error();445}446447{ BMK_runTime_t const cResult = BMK_extract_runTime(cOutcome);448cSize = cResult.sumOfReturn;449ratio = (double)srcSize / (double)cSize;450{ BMK_benchResult_t newResult;451newResult.cSpeed = (U64)((double)srcSize * TIMELOOP_NANOSEC / cResult.nanoSecPerRun);452benchResult.cSize = cSize;453if (newResult.cSpeed > benchResult.cSpeed)454benchResult.cSpeed = newResult.cSpeed;455} }456457{ int const ratioAccuracy = (ratio < 10.) ? 3 : 2;458assert(cSize < UINT_MAX);459OUTPUTLEVEL(2, "%2s-%-17.17s :%10u ->%10u (x%5.*f), %6.*f MB/s \r",460marks[markNb], displayName,461(unsigned)srcSize, (unsigned)cSize,462ratioAccuracy, ratio,463benchResult.cSpeed < (10 * MB_UNIT) ? 2 : 1, (double)benchResult.cSpeed / MB_UNIT);464}465compressionCompleted = BMK_isCompleted_TimedFn(timeStateCompress);466}467468if(!decompressionCompleted) {469BMK_runOutcome_t const dOutcome = BMK_benchTimedFn(timeStateDecompress, dbp);470471if(!BMK_isSuccessful_runOutcome(dOutcome)) {472return BMK_benchOutcome_error();473}474475{ BMK_runTime_t const dResult = BMK_extract_runTime(dOutcome);476U64 const newDSpeed = (U64)((double)srcSize * TIMELOOP_NANOSEC / dResult.nanoSecPerRun);477if (newDSpeed > benchResult.dSpeed)478benchResult.dSpeed = newDSpeed;479}480481{ int const ratioAccuracy = (ratio < 10.) ? 3 : 2;482OUTPUTLEVEL(2, "%2s-%-17.17s :%10u ->%10u (x%5.*f), %6.*f MB/s, %6.1f MB/s\r",483marks[markNb], displayName,484(unsigned)srcSize, (unsigned)cSize,485ratioAccuracy, ratio,486benchResult.cSpeed < (10 * MB_UNIT) ? 2 : 1, (double)benchResult.cSpeed / MB_UNIT,487(double)benchResult.dSpeed / MB_UNIT);488}489decompressionCompleted = BMK_isCompleted_TimedFn(timeStateDecompress);490}491markNb = (markNb+1) % NB_MARKS;492} /* while (!(compressionCompleted && decompressionCompleted)) */493494/* CRC Checking */495{ const BYTE* resultBuffer = (const BYTE*)(*resultBufferPtr);496U64 const crcCheck = XXH64(resultBuffer, srcSize, 0);497if ((adv->mode == BMK_both) && (crcOrig!=crcCheck)) {498size_t u;499DISPLAY("!!! WARNING !!! %14s : Invalid Checksum : %x != %x \n",500displayName, (unsigned)crcOrig, (unsigned)crcCheck);501for (u=0; u<srcSize; u++) {502if (((const BYTE*)srcBuffer)[u] != resultBuffer[u]) {503unsigned segNb, bNb, pos;504size_t bacc = 0;505DISPLAY("Decoding error at pos %u ", (unsigned)u);506for (segNb = 0; segNb < nbBlocks; segNb++) {507if (bacc + srcSizes[segNb] > u) break;508bacc += srcSizes[segNb];509}510pos = (U32)(u - bacc);511bNb = pos / (128 KB);512DISPLAY("(sample %u, block %u, pos %u) \n", segNb, bNb, pos);513{ size_t const lowest = (u>5) ? 5 : u;514size_t n;515DISPLAY("origin: ");516for (n=lowest; n>0; n--)517DISPLAY("%02X ", ((const BYTE*)srcBuffer)[u-n]);518DISPLAY(" :%02X: ", ((const BYTE*)srcBuffer)[u]);519for (n=1; n<3; n++)520DISPLAY("%02X ", ((const BYTE*)srcBuffer)[u+n]);521DISPLAY(" \n");522DISPLAY("decode: ");523for (n=lowest; n>0; n--)524DISPLAY("%02X ", resultBuffer[u-n]);525DISPLAY(" :%02X: ", resultBuffer[u]);526for (n=1; n<3; n++)527DISPLAY("%02X ", resultBuffer[u+n]);528DISPLAY(" \n");529}530break;531}532if (u==srcSize-1) { /* should never happen */533DISPLAY("no difference detected\n");534}535} /* for (u=0; u<srcSize; u++) */536} /* if ((adv->mode == BMK_both) && (crcOrig!=crcCheck)) */537} /* CRC Checking */538539if (displayLevel == 1) { /* hidden display mode -q, used by python speed benchmark */540double const cSpeed = (double)benchResult.cSpeed / MB_UNIT;541double const dSpeed = (double)benchResult.dSpeed / MB_UNIT;542if (adv->additionalParam) {543OUTPUT("-%-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);544} else {545OUTPUT("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s %s\n", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName);546}547}548549OUTPUTLEVEL(2, "%2i#\n", cLevel);550} /* Bench */551552benchResult.cMem = (1ULL << (comprParams->windowLog)) + ZSTD_sizeof_CCtx(cctx);553return BMK_benchOutcome_setValidResult(benchResult);554}555556BMK_benchOutcome_t BMK_benchMemAdvanced(const void* srcBuffer, size_t srcSize,557void* dstBuffer, size_t dstCapacity,558const size_t* fileSizes, unsigned nbFiles,559int cLevel, const ZSTD_compressionParameters* comprParams,560const void* dictBuffer, size_t dictBufferSize,561int displayLevel, const char* displayName, const BMK_advancedParams_t* adv)562563{564int const dstParamsError = !dstBuffer ^ !dstCapacity; /* must be both NULL or none */565566size_t const blockSize = ((adv->blockSize>=32 && (adv->mode != BMK_decodeOnly)) ? adv->blockSize : srcSize) + (!srcSize) /* avoid div by 0 */ ;567U32 const maxNbBlocks = (U32) ((srcSize + (blockSize-1)) / blockSize) + nbFiles;568569/* these are the blockTable parameters, just split up */570const void ** const srcPtrs = (const void**)malloc(maxNbBlocks * sizeof(void*));571size_t* const srcSizes = (size_t*)malloc(maxNbBlocks * sizeof(size_t));572573574void ** const cPtrs = (void**)malloc(maxNbBlocks * sizeof(void*));575size_t* const cSizes = (size_t*)malloc(maxNbBlocks * sizeof(size_t));576size_t* const cCapacities = (size_t*)malloc(maxNbBlocks * sizeof(size_t));577578void ** const resPtrs = (void**)malloc(maxNbBlocks * sizeof(void*));579size_t* const resSizes = (size_t*)malloc(maxNbBlocks * sizeof(size_t));580581BMK_timedFnState_t* timeStateCompress = BMK_createTimedFnState(adv->nbSeconds * 1000, BMK_RUNTEST_DEFAULT_MS);582BMK_timedFnState_t* timeStateDecompress = BMK_createTimedFnState(adv->nbSeconds * 1000, BMK_RUNTEST_DEFAULT_MS);583584ZSTD_CCtx* const cctx = ZSTD_createCCtx();585ZSTD_DCtx* const dctx = ZSTD_createDCtx();586587const size_t maxCompressedSize = dstCapacity ? dstCapacity : ZSTD_compressBound(srcSize) + (maxNbBlocks * 1024);588589void* const internalDstBuffer = dstBuffer ? NULL : malloc(maxCompressedSize);590void* const compressedBuffer = dstBuffer ? dstBuffer : internalDstBuffer;591592BMK_benchOutcome_t outcome = BMK_benchOutcome_error(); /* error by default */593594void* resultBuffer = srcSize ? malloc(srcSize) : NULL;595596int allocationincomplete = !srcPtrs || !srcSizes || !cPtrs ||597!cSizes || !cCapacities || !resPtrs || !resSizes ||598!timeStateCompress || !timeStateDecompress ||599!cctx || !dctx ||600!compressedBuffer || !resultBuffer;601602603if (!allocationincomplete && !dstParamsError) {604outcome = BMK_benchMemAdvancedNoAlloc(srcPtrs, srcSizes,605cPtrs, cCapacities, cSizes,606resPtrs, resSizes,607&resultBuffer,608compressedBuffer, maxCompressedSize,609timeStateCompress, timeStateDecompress,610srcBuffer, srcSize,611fileSizes, nbFiles,612cLevel, comprParams,613dictBuffer, dictBufferSize,614cctx, dctx,615displayLevel, displayName, adv);616}617618/* clean up */619BMK_freeTimedFnState(timeStateCompress);620BMK_freeTimedFnState(timeStateDecompress);621622ZSTD_freeCCtx(cctx);623ZSTD_freeDCtx(dctx);624625free(internalDstBuffer);626free(resultBuffer);627628free((void*)srcPtrs);629free(srcSizes);630free(cPtrs);631free(cSizes);632free(cCapacities);633free(resPtrs);634free(resSizes);635636if(allocationincomplete) {637RETURN_ERROR(31, BMK_benchOutcome_t, "allocation error : not enough memory");638}639640if(dstParamsError) {641RETURN_ERROR(32, BMK_benchOutcome_t, "Dst parameters not coherent");642}643return outcome;644}645646BMK_benchOutcome_t BMK_benchMem(const void* srcBuffer, size_t srcSize,647const size_t* fileSizes, unsigned nbFiles,648int cLevel, const ZSTD_compressionParameters* comprParams,649const void* dictBuffer, size_t dictBufferSize,650int displayLevel, const char* displayName) {651652BMK_advancedParams_t const adv = BMK_initAdvancedParams();653return BMK_benchMemAdvanced(srcBuffer, srcSize,654NULL, 0,655fileSizes, nbFiles,656cLevel, comprParams,657dictBuffer, dictBufferSize,658displayLevel, displayName, &adv);659}660661static BMK_benchOutcome_t BMK_benchCLevel(const void* srcBuffer, size_t benchedSize,662const size_t* fileSizes, unsigned nbFiles,663int cLevel, const ZSTD_compressionParameters* comprParams,664const void* dictBuffer, size_t dictBufferSize,665int displayLevel, const char* displayName,666BMK_advancedParams_t const * const adv)667{668const char* pch = strrchr(displayName, '\\'); /* Windows */669if (!pch) pch = strrchr(displayName, '/'); /* Linux */670if (pch) displayName = pch+1;671672if (adv->realTime) {673DISPLAYLEVEL(2, "Note : switching to real-time priority \n");674SET_REALTIME_PRIORITY;675}676677if (displayLevel == 1 && !adv->additionalParam) /* --quiet mode */678OUTPUT("bench %s %s: input %u bytes, %u seconds, %u KB blocks\n",679ZSTD_VERSION_STRING, ZSTD_GIT_COMMIT_STRING,680(unsigned)benchedSize, adv->nbSeconds, (unsigned)(adv->blockSize>>10));681682return BMK_benchMemAdvanced(srcBuffer, benchedSize,683NULL, 0,684fileSizes, nbFiles,685cLevel, comprParams,686dictBuffer, dictBufferSize,687displayLevel, displayName, adv);688}689690BMK_benchOutcome_t BMK_syntheticTest(int cLevel, double compressibility,691const ZSTD_compressionParameters* compressionParams,692int displayLevel, const BMK_advancedParams_t* adv)693{694char name[20] = {0};695size_t const benchedSize = 10000000;696void* srcBuffer;697BMK_benchOutcome_t res;698699if (cLevel > ZSTD_maxCLevel()) {700RETURN_ERROR(15, BMK_benchOutcome_t, "Invalid Compression Level");701}702703/* Memory allocation */704srcBuffer = malloc(benchedSize);705if (!srcBuffer) RETURN_ERROR(21, BMK_benchOutcome_t, "not enough memory");706707/* Fill input buffer */708RDG_genBuffer(srcBuffer, benchedSize, compressibility, 0.0, 0);709710/* Bench */711snprintf (name, sizeof(name), "Synthetic %2u%%", (unsigned)(compressibility*100));712res = BMK_benchCLevel(srcBuffer, benchedSize,713&benchedSize /* ? */, 1 /* ? */,714cLevel, compressionParams,715NULL, 0, /* dictionary */716displayLevel, name, adv);717718/* clean up */719free(srcBuffer);720721return res;722}723724725726static size_t BMK_findMaxMem(U64 requiredMem)727{728size_t const step = 64 MB;729BYTE* testmem = NULL;730731requiredMem = (((requiredMem >> 26) + 1) << 26);732requiredMem += step;733if (requiredMem > maxMemory) requiredMem = maxMemory;734735do {736testmem = (BYTE*)malloc((size_t)requiredMem);737requiredMem -= step;738} while (!testmem && requiredMem > 0);739740free(testmem);741return (size_t)(requiredMem);742}743744/*! BMK_loadFiles() :745* Loads `buffer` with content of files listed within `fileNamesTable`.746* At most, fills `buffer` entirely. */747static int BMK_loadFiles(void* buffer, size_t bufferSize,748size_t* fileSizes,749const char* const * fileNamesTable, unsigned nbFiles,750int displayLevel)751{752size_t pos = 0, totalSize = 0;753unsigned n;754for (n=0; n<nbFiles; n++) {755U64 fileSize = UTIL_getFileSize(fileNamesTable[n]); /* last file may be shortened */756if (UTIL_isDirectory(fileNamesTable[n])) {757DISPLAYLEVEL(2, "Ignoring %s directory... \n", fileNamesTable[n]);758fileSizes[n] = 0;759continue;760}761if (fileSize == UTIL_FILESIZE_UNKNOWN) {762DISPLAYLEVEL(2, "Cannot evaluate size of %s, ignoring ... \n", fileNamesTable[n]);763fileSizes[n] = 0;764continue;765}766{ FILE* const f = fopen(fileNamesTable[n], "rb");767if (f==NULL) RETURN_ERROR_INT(10, "impossible to open file %s", fileNamesTable[n]);768OUTPUTLEVEL(2, "Loading %s... \r", fileNamesTable[n]);769if (fileSize > bufferSize-pos) fileSize = bufferSize-pos, nbFiles=n; /* buffer too small - stop after this file */770{ size_t const readSize = fread(((char*)buffer)+pos, 1, (size_t)fileSize, f);771if (readSize != (size_t)fileSize) RETURN_ERROR_INT(11, "could not read %s", fileNamesTable[n]);772pos += readSize;773}774fileSizes[n] = (size_t)fileSize;775totalSize += (size_t)fileSize;776fclose(f);777} }778779if (totalSize == 0) RETURN_ERROR_INT(12, "no data to bench");780return 0;781}782783BMK_benchOutcome_t BMK_benchFilesAdvanced(784const char* const * fileNamesTable, unsigned nbFiles,785const char* dictFileName, int cLevel,786const ZSTD_compressionParameters* compressionParams,787int displayLevel, const BMK_advancedParams_t* adv)788{789void* srcBuffer = NULL;790size_t benchedSize;791void* dictBuffer = NULL;792size_t dictBufferSize = 0;793size_t* fileSizes = NULL;794BMK_benchOutcome_t res;795U64 const totalSizeToLoad = UTIL_getTotalFileSize(fileNamesTable, nbFiles);796797if (!nbFiles) {798RETURN_ERROR(14, BMK_benchOutcome_t, "No Files to Benchmark");799}800801if (cLevel > ZSTD_maxCLevel()) {802RETURN_ERROR(15, BMK_benchOutcome_t, "Invalid Compression Level");803}804805if (totalSizeToLoad == UTIL_FILESIZE_UNKNOWN) {806RETURN_ERROR(9, BMK_benchOutcome_t, "Error loading files");807}808809fileSizes = (size_t*)calloc(nbFiles, sizeof(size_t));810if (!fileSizes) RETURN_ERROR(12, BMK_benchOutcome_t, "not enough memory for fileSizes");811812/* Load dictionary */813if (dictFileName != NULL) {814U64 const dictFileSize = UTIL_getFileSize(dictFileName);815if (dictFileSize == UTIL_FILESIZE_UNKNOWN) {816DISPLAYLEVEL(1, "error loading %s : %s \n", dictFileName, strerror(errno));817free(fileSizes);818RETURN_ERROR(9, BMK_benchOutcome_t, "benchmark aborted");819}820if (dictFileSize > 64 MB) {821free(fileSizes);822RETURN_ERROR(10, BMK_benchOutcome_t, "dictionary file %s too large", dictFileName);823}824dictBufferSize = (size_t)dictFileSize;825dictBuffer = malloc(dictBufferSize);826if (dictBuffer==NULL) {827free(fileSizes);828RETURN_ERROR(11, BMK_benchOutcome_t, "not enough memory for dictionary (%u bytes)",829(unsigned)dictBufferSize);830}831832{ int const errorCode = BMK_loadFiles(dictBuffer, dictBufferSize,833fileSizes, &dictFileName /*?*/,8341 /*?*/, displayLevel);835if (errorCode) {836res = BMK_benchOutcome_error();837goto _cleanUp;838} }839}840841/* Memory allocation & restrictions */842benchedSize = BMK_findMaxMem(totalSizeToLoad * 3) / 3;843if ((U64)benchedSize > totalSizeToLoad) benchedSize = (size_t)totalSizeToLoad;844if (benchedSize < totalSizeToLoad)845DISPLAY("Not enough memory; testing %u MB only...\n", (unsigned)(benchedSize >> 20));846847srcBuffer = benchedSize ? malloc(benchedSize) : NULL;848if (!srcBuffer) {849free(dictBuffer);850free(fileSizes);851RETURN_ERROR(12, BMK_benchOutcome_t, "not enough memory");852}853854/* Load input buffer */855{ int const errorCode = BMK_loadFiles(srcBuffer, benchedSize,856fileSizes, fileNamesTable, nbFiles,857displayLevel);858if (errorCode) {859res = BMK_benchOutcome_error();860goto _cleanUp;861} }862863/* Bench */864{ char mfName[20] = {0};865snprintf (mfName, sizeof(mfName), " %u files", nbFiles);866{ const char* const displayName = (nbFiles > 1) ? mfName : fileNamesTable[0];867res = BMK_benchCLevel(srcBuffer, benchedSize,868fileSizes, nbFiles,869cLevel, compressionParams,870dictBuffer, dictBufferSize,871displayLevel, displayName,872adv);873} }874875_cleanUp:876free(srcBuffer);877free(dictBuffer);878free(fileSizes);879return res;880}881882883BMK_benchOutcome_t BMK_benchFiles(884const char* const * fileNamesTable, unsigned nbFiles,885const char* dictFileName,886int cLevel, const ZSTD_compressionParameters* compressionParams,887int displayLevel)888{889BMK_advancedParams_t const adv = BMK_initAdvancedParams();890return BMK_benchFilesAdvanced(fileNamesTable, nbFiles, dictFileName, cLevel, compressionParams, displayLevel, &adv);891}892893894