1 /*
2     bench.c - Demo program to benchmark open-source compression algorithm
3     Copyright (C) Yann Collet 2012-2020
4 
5     GPL v2 License
6 
7     This program is free software; you can redistribute it and/or modify
8     it under the terms of the GNU General Public License as published by
9     the Free Software Foundation; either version 2 of the License, or
10     (at your option) any later version.
11 
12     This program is distributed in the hope that it will be useful,
13     but WITHOUT ANY WARRANTY; without even the implied warranty of
14     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15     GNU General Public License for more details.
16 
17     You should have received a copy of the GNU General Public License along
18     with this program; if not, write to the Free Software Foundation, Inc.,
19     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 
21     You can contact the author at :
22     - LZ4 source repository : https://github.com/lz4/lz4
23     - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
24 */
25 
26 
27 #if defined(_MSC_VER) || defined(_WIN32)
28    /* S_ISREG & gettimeofday() are not supported by MSVC */
29 #  define BMK_LEGACY_TIMER 1
30 #endif
31 
32 
33 /**************************************
34 *  Includes
35 **************************************/
36 #include "platform.h"    /* _CRT_SECURE_NO_WARNINGS, Large Files support */
37 #include "util.h"        /* U32, UTIL_getFileSize */
38 #include <stdlib.h>      /* malloc, free */
39 #include <stdio.h>       /* fprintf, fopen, ftello */
40 #include <sys/types.h>   /* stat64 */
41 #include <sys/stat.h>    /* stat64 */
42 #include <string.h>      /* strcmp */
43 #include <time.h>        /* clock_t, clock(), CLOCKS_PER_SEC */
44 
45 #define LZ4_DISABLE_DEPRECATE_WARNINGS   /* LZ4_decompress_fast */
46 #include "lz4.h"
47 #include "lz4hc.h"
48 #include "lz4frame.h"
49 
50 #include "xxhash.h"
51 
52 
53 /**************************************
54 *  Constants
55 **************************************/
56 #define PROGRAM_DESCRIPTION "LZ4 speed analyzer"
57 #define AUTHOR "Yann Collet"
58 #define WELCOME_MESSAGE "*** %s v%s %i-bits, by %s ***\n", PROGRAM_DESCRIPTION, LZ4_VERSION_STRING, (int)(sizeof(void*)*8), AUTHOR
59 
60 #define NBLOOPS    6
61 #define TIMELOOP   (CLOCKS_PER_SEC * 25 / 10)
62 
63 #define KB *(1 <<10)
64 #define MB *(1 <<20)
65 #define GB *(1U<<30)
66 
67 #define KNUTH      2654435761U
68 #define MAX_MEM    (1920 MB)
69 #define DEFAULT_CHUNKSIZE   (4 MB)
70 
71 #define ALL_COMPRESSORS 0
72 #define ALL_DECOMPRESSORS 0
73 
74 
75 /**************************************
76 *  Local structures
77 **************************************/
78 struct chunkParameters
79 {
80     U32   id;
81     char* origBuffer;
82     char* compressedBuffer;
83     int   origSize;
84     int   compressedSize;
85 };
86 
87 
88 /**************************************
89 *  Macros
90 **************************************/
91 #define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
92 #define PROGRESS(...) g_noPrompt ? 0 : DISPLAY(__VA_ARGS__)
93 
94 
95 /**************************************
96 *  Benchmark Parameters
97 **************************************/
98 static int g_chunkSize = DEFAULT_CHUNKSIZE;
99 static int g_nbIterations = NBLOOPS;
100 static int g_pause = 0;
101 static int g_compressionTest = 1;
102 static int g_compressionAlgo = ALL_COMPRESSORS;
103 static int g_decompressionTest = 1;
104 static int g_decompressionAlgo = ALL_DECOMPRESSORS;
105 static int g_noPrompt = 0;
106 
BMK_setBlocksize(int bsize)107 static void BMK_setBlocksize(int bsize)
108 {
109     g_chunkSize = bsize;
110     DISPLAY("-Using Block Size of %i KB-\n", g_chunkSize>>10);
111 }
112 
BMK_setNbIterations(int nbLoops)113 static void BMK_setNbIterations(int nbLoops)
114 {
115     g_nbIterations = nbLoops;
116     DISPLAY("- %i iterations -\n", g_nbIterations);
117 }
118 
BMK_setPause(void)119 static void BMK_setPause(void)
120 {
121     g_pause = 1;
122 }
123 
124 
125 /*********************************************************
126 *  Private functions
127 *********************************************************/
BMK_GetClockSpan(clock_t clockStart)128 static clock_t BMK_GetClockSpan( clock_t clockStart )
129 {
130     return clock() - clockStart;   /* works even if overflow; max span ~30 mn */
131 }
132 
133 
BMK_findMaxMem(U64 requiredMem)134 static size_t BMK_findMaxMem(U64 requiredMem)
135 {
136     size_t step = 64 MB;
137     BYTE* testmem = NULL;
138 
139     requiredMem = (((requiredMem >> 26) + 1) << 26);
140     requiredMem += 2*step;
141     if (requiredMem > MAX_MEM) requiredMem = MAX_MEM;
142 
143     while (!testmem) {
144         if (requiredMem > step) requiredMem -= step;
145         else requiredMem >>= 1;
146         testmem = (BYTE*) malloc ((size_t)requiredMem);
147     }
148     free (testmem);
149 
150     /* keep some space available */
151     if (requiredMem > step) requiredMem -= step;
152     else requiredMem >>= 1;
153 
154     return (size_t)requiredMem;
155 }
156 
157 
158 /*********************************************************
159 *  Memory management, to test LZ4_USER_MEMORY_FUNCTIONS
160 *********************************************************/
LZ4_malloc(size_t s)161 void* LZ4_malloc(size_t s) { return malloc(s); }
LZ4_calloc(size_t n,size_t s)162 void* LZ4_calloc(size_t n, size_t s) { return calloc(n,s); }
LZ4_free(void * p)163 void  LZ4_free(void* p) { free(p); }
164 
165 
166 /*********************************************************
167 *  Benchmark function
168 *********************************************************/
169 static LZ4_stream_t LZ4_stream;
local_LZ4_resetDictT(void)170 static void local_LZ4_resetDictT(void)
171 {
172     void* const r = LZ4_initStream(&LZ4_stream, sizeof(LZ4_stream));
173     assert(r != NULL); (void)r;
174 }
175 
local_LZ4_createStream(void)176 static void local_LZ4_createStream(void)
177 {
178     void* const r = LZ4_initStream(&LZ4_stream, sizeof(LZ4_stream));
179     assert(r != NULL); (void)r;
180 }
181 
local_LZ4_saveDict(const char * in,char * out,int inSize)182 static int local_LZ4_saveDict(const char* in, char* out, int inSize)
183 {
184     (void)in;
185     return LZ4_saveDict(&LZ4_stream, out, inSize);
186 }
187 
local_LZ4_compress_default_large(const char * in,char * out,int inSize)188 static int local_LZ4_compress_default_large(const char* in, char* out, int inSize)
189 {
190     return LZ4_compress_default(in, out, inSize, LZ4_compressBound(inSize));
191 }
192 
local_LZ4_compress_default_small(const char * in,char * out,int inSize)193 static int local_LZ4_compress_default_small(const char* in, char* out, int inSize)
194 {
195     return LZ4_compress_default(in, out, inSize, LZ4_compressBound(inSize)-1);
196 }
197 
local_LZ4_compress_destSize(const char * in,char * out,int inSize)198 static int local_LZ4_compress_destSize(const char* in, char* out, int inSize)
199 {
200     return LZ4_compress_destSize(in, out, &inSize, LZ4_compressBound(inSize)-1);
201 }
202 
local_LZ4_compress_fast0(const char * in,char * out,int inSize)203 static int local_LZ4_compress_fast0(const char* in, char* out, int inSize)
204 {
205     return LZ4_compress_fast(in, out, inSize, LZ4_compressBound(inSize), 0);
206 }
207 
local_LZ4_compress_fast1(const char * in,char * out,int inSize)208 static int local_LZ4_compress_fast1(const char* in, char* out, int inSize)
209 {
210     return LZ4_compress_fast(in, out, inSize, LZ4_compressBound(inSize), 1);
211 }
212 
local_LZ4_compress_fast2(const char * in,char * out,int inSize)213 static int local_LZ4_compress_fast2(const char* in, char* out, int inSize)
214 {
215     return LZ4_compress_fast(in, out, inSize, LZ4_compressBound(inSize), 2);
216 }
217 
local_LZ4_compress_fast17(const char * in,char * out,int inSize)218 static int local_LZ4_compress_fast17(const char* in, char* out, int inSize)
219 {
220     return LZ4_compress_fast(in, out, inSize, LZ4_compressBound(inSize), 17);
221 }
222 
local_LZ4_compress_fast_extState0(const char * in,char * out,int inSize)223 static int local_LZ4_compress_fast_extState0(const char* in, char* out, int inSize)
224 {
225     return LZ4_compress_fast_extState(&LZ4_stream, in, out, inSize, LZ4_compressBound(inSize), 0);
226 }
227 
local_LZ4_compress_fast_continue0(const char * in,char * out,int inSize)228 static int local_LZ4_compress_fast_continue0(const char* in, char* out, int inSize)
229 {
230     return LZ4_compress_fast_continue(&LZ4_stream, in, out, inSize, LZ4_compressBound(inSize), 0);
231 }
232 
233 #ifndef LZ4_DLL_IMPORT
234 #if defined (__cplusplus)
235 extern "C" {
236 #endif
237 
238 /* declare hidden function */
239 extern int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize);
240 
241 #if defined (__cplusplus)
242 }
243 #endif
244 
local_LZ4_compress_forceDict(const char * in,char * out,int inSize)245 static int local_LZ4_compress_forceDict(const char* in, char* out, int inSize)
246 {
247     return LZ4_compress_forceExtDict(&LZ4_stream, in, out, inSize);
248 }
249 #endif
250 
251 
252 /* HC compression functions */
253 LZ4_streamHC_t LZ4_streamHC;
local_LZ4_resetStreamHC(void)254 static void local_LZ4_resetStreamHC(void)
255 {
256     LZ4_initStreamHC(&LZ4_streamHC, sizeof(LZ4_streamHC));
257 }
258 
local_LZ4_saveDictHC(const char * in,char * out,int inSize)259 static int local_LZ4_saveDictHC(const char* in, char* out, int inSize)
260 {
261     (void)in;
262     return LZ4_saveDictHC(&LZ4_streamHC, out, inSize);
263 }
264 
local_LZ4_compress_HC(const char * in,char * out,int inSize)265 static int local_LZ4_compress_HC(const char* in, char* out, int inSize)
266 {
267     return LZ4_compress_HC(in, out, inSize, LZ4_compressBound(inSize), 9);
268 }
269 
local_LZ4_compress_HC_extStateHC(const char * in,char * out,int inSize)270 static int local_LZ4_compress_HC_extStateHC(const char* in, char* out, int inSize)
271 {
272     return LZ4_compress_HC_extStateHC(&LZ4_streamHC, in, out, inSize, LZ4_compressBound(inSize), 9);
273 }
274 
local_LZ4_compress_HC_continue(const char * in,char * out,int inSize)275 static int local_LZ4_compress_HC_continue(const char* in, char* out, int inSize)
276 {
277     return LZ4_compress_HC_continue(&LZ4_streamHC, in, out, inSize, LZ4_compressBound(inSize));
278 }
279 
280 
281 /* decompression functions */
local_LZ4_decompress_fast(const char * in,char * out,int inSize,int outSize)282 static int local_LZ4_decompress_fast(const char* in, char* out, int inSize, int outSize)
283 {
284     (void)inSize;
285     LZ4_decompress_fast(in, out, outSize);
286     return outSize;
287 }
288 
local_LZ4_decompress_fast_usingDict_prefix(const char * in,char * out,int inSize,int outSize)289 static int local_LZ4_decompress_fast_usingDict_prefix(const char* in, char* out, int inSize, int outSize)
290 {
291     (void)inSize;
292     LZ4_decompress_fast_usingDict(in, out, outSize, out - 65536, 65536);
293     return outSize;
294 }
295 
local_LZ4_decompress_fast_usingExtDict(const char * in,char * out,int inSize,int outSize)296 static int local_LZ4_decompress_fast_usingExtDict(const char* in, char* out, int inSize, int outSize)
297 {
298     (void)inSize;
299     LZ4_decompress_fast_usingDict(in, out, outSize, out - 65536, 65535);
300     return outSize;
301 }
302 
local_LZ4_decompress_safe_withPrefix64k(const char * in,char * out,int inSize,int outSize)303 static int local_LZ4_decompress_safe_withPrefix64k(const char* in, char* out, int inSize, int outSize)
304 {
305     LZ4_decompress_safe_withPrefix64k(in, out, inSize, outSize);
306     return outSize;
307 }
308 
local_LZ4_decompress_safe_usingDict(const char * in,char * out,int inSize,int outSize)309 static int local_LZ4_decompress_safe_usingDict(const char* in, char* out, int inSize, int outSize)
310 {
311     LZ4_decompress_safe_usingDict(in, out, inSize, outSize, out - 65536, 65536);
312     return outSize;
313 }
314 
315 #ifndef LZ4_DLL_IMPORT
316 #if defined (__cplusplus)
317 extern "C" {
318 #endif
319 
320 extern int LZ4_decompress_safe_forceExtDict(const char* in, char* out, int inSize, int outSize, const void* dict, size_t dictSize);
321 
322 #if defined (__cplusplus)
323 }
324 #endif
325 
local_LZ4_decompress_safe_forceExtDict(const char * in,char * out,int inSize,int outSize)326 static int local_LZ4_decompress_safe_forceExtDict(const char* in, char* out, int inSize, int outSize)
327 {
328     (void)inSize;
329     LZ4_decompress_safe_forceExtDict(in, out, inSize, outSize, out - 65536, 65536);
330     return outSize;
331 }
332 #endif
333 
local_LZ4_decompress_safe_partial(const char * in,char * out,int inSize,int outSize)334 static int local_LZ4_decompress_safe_partial(const char* in, char* out, int inSize, int outSize)
335 {
336     int result = LZ4_decompress_safe_partial(in, out, inSize, outSize - 5, outSize);
337     if (result < 0) return result;
338     return outSize;
339 }
340 
341 
342 /* frame functions */
local_LZ4F_compressFrame(const char * in,char * out,int inSize)343 static int local_LZ4F_compressFrame(const char* in, char* out, int inSize)
344 {
345     assert(inSize >= 0);
346     return (int)LZ4F_compressFrame(out, LZ4F_compressFrameBound((size_t)inSize, NULL), in, (size_t)inSize, NULL);
347 }
348 
349 static LZ4F_decompressionContext_t g_dCtx;
350 
local_LZ4F_decompress(const char * in,char * out,int inSize,int outSize)351 static int local_LZ4F_decompress(const char* in, char* out, int inSize, int outSize)
352 {
353     size_t srcSize = (size_t)inSize;
354     size_t dstSize = (size_t)outSize;
355     size_t result;
356     assert(inSize >= 0);
357     assert(outSize >= 0);
358     result = LZ4F_decompress(g_dCtx, out, &dstSize, in, &srcSize, NULL);
359     if (result!=0) { DISPLAY("Error decompressing frame : unfinished frame \n"); exit(8); }
360     if (srcSize != (size_t)inSize) { DISPLAY("Error decompressing frame : read size incorrect \n"); exit(9); }
361     return (int)dstSize;
362 }
363 
local_LZ4F_decompress_followHint(const char * src,char * dst,int srcSize,int dstSize)364 static int local_LZ4F_decompress_followHint(const char* src, char* dst, int srcSize, int dstSize)
365 {
366     size_t totalInSize = (size_t)srcSize;
367     size_t maxOutSize = (size_t)dstSize;
368 
369     size_t inPos = 0;
370     size_t inSize = 0;
371     size_t outPos = 0;
372     size_t outRemaining = maxOutSize - outPos;
373 
374     for (;;) {
375         size_t const sizeHint = LZ4F_decompress(g_dCtx, dst+outPos, &outRemaining, src+inPos, &inSize, NULL);
376         assert(!LZ4F_isError(sizeHint));
377 
378         inPos += inSize;
379         inSize = sizeHint;
380 
381         outPos += outRemaining;
382         outRemaining = maxOutSize - outPos;
383 
384         if (!sizeHint) break;
385     }
386 
387     /* frame completed */
388     if (inPos != totalInSize) {
389         DISPLAY("Error decompressing frame : must read (%u) full frame (%u) \n",
390                 (unsigned)inPos, (unsigned)totalInSize);
391         exit(10);
392     }
393     return (int)outPos;
394 
395 }
396 
397 /* always provide input by block of 64 KB */
local_LZ4F_decompress_noHint(const char * src,char * dst,int srcSize,int dstSize)398 static int local_LZ4F_decompress_noHint(const char* src, char* dst, int srcSize, int dstSize)
399 {
400     size_t totalInSize = (size_t)srcSize;
401     size_t maxOutSize = (size_t)dstSize;
402 
403     size_t inPos = 0;
404     size_t inSize = 64 KB;
405     size_t outPos = 0;
406     size_t outRemaining = maxOutSize - outPos;
407 
408     for (;;) {
409         size_t const sizeHint = LZ4F_decompress(g_dCtx, dst+outPos, &outRemaining, src+inPos, &inSize, NULL);
410         assert(!LZ4F_isError(sizeHint));
411 
412         inPos += inSize;
413         inSize = (inPos + 64 KB <= totalInSize) ? 64 KB : totalInSize - inPos;
414 
415         outPos += outRemaining;
416         outRemaining = maxOutSize - outPos;
417 
418         if (!sizeHint) break;
419     }
420 
421     /* frame completed */
422     if (inPos != totalInSize) {
423         DISPLAY("Error decompressing frame : must read (%u) full frame (%u) \n",
424                 (unsigned)inPos, (unsigned)totalInSize);
425         exit(10);
426     }
427     return (int)outPos;
428 
429 }
430 
431 #define NB_COMPRESSION_ALGORITHMS 100
432 #define NB_DECOMPRESSION_ALGORITHMS 100
fullSpeedBench(const char ** fileNamesTable,int nbFiles)433 int fullSpeedBench(const char** fileNamesTable, int nbFiles)
434 {
435     int fileIdx=0;
436 
437     /* Init */
438     { size_t const errorCode = LZ4F_createDecompressionContext(&g_dCtx, LZ4F_VERSION);
439       if (LZ4F_isError(errorCode)) { DISPLAY("dctx allocation issue \n"); return 10; } }
440 
441     /* Loop for each fileName */
442     while (fileIdx<nbFiles) {
443       char* orig_buff = NULL;
444       struct chunkParameters* chunkP = NULL;
445       char* compressed_buff=NULL;
446       const char* const inFileName = fileNamesTable[fileIdx++];
447       FILE* const inFile = fopen( inFileName, "rb" );
448       U64 const inFileSize = UTIL_getFileSize(inFileName);
449       size_t benchedSize = BMK_findMaxMem(inFileSize*2) / 2;   /* because 2 buffers */
450       int nbChunks;
451       int maxCompressedChunkSize;
452       size_t readSize;
453       int compressedBuffSize;
454       U32 crcOriginal;
455 
456       /* Check infile pre-requisites */
457       if (inFile==NULL) { DISPLAY("Pb opening %s \n", inFileName); return 11; }
458       if (inFileSize==0) { DISPLAY("file is empty \n"); fclose(inFile); return 11; }
459       if (benchedSize==0) { DISPLAY("not enough memory \n"); fclose(inFile); return 11; }
460 
461       /* Memory size adjustments */
462       if ((U64)benchedSize > inFileSize) benchedSize = (size_t)inFileSize;
463       if (benchedSize < inFileSize) {
464           DISPLAY("Not enough memory for '%s' full size; testing %i MB only... \n",
465                 inFileName, (int)(benchedSize>>20));
466       }
467 
468       /* Allocation */
469       chunkP = (struct chunkParameters*) malloc(((benchedSize / (size_t)g_chunkSize)+1) * sizeof(struct chunkParameters));
470       orig_buff = (char*) malloc(benchedSize);
471       nbChunks = (int) ((benchedSize + (size_t)g_chunkSize - 1) / (size_t)g_chunkSize);
472       maxCompressedChunkSize = LZ4_compressBound(g_chunkSize);
473       compressedBuffSize = nbChunks * maxCompressedChunkSize;
474       compressed_buff = (char*)malloc((size_t)compressedBuffSize);
475       if(!chunkP || !orig_buff || !compressed_buff) {
476           DISPLAY("\nError: not enough memory! \n");
477           fclose(inFile);
478           free(orig_buff);
479           free(compressed_buff);
480           free(chunkP);
481           return(12);
482       }
483 
484       /* Fill in src buffer */
485       DISPLAY("Loading %s...       \r", inFileName);
486       readSize = fread(orig_buff, 1, benchedSize, inFile);
487       fclose(inFile);
488 
489       if (readSize != benchedSize) {
490         DISPLAY("\nError: problem reading file '%s' !!    \n", inFileName);
491         free(orig_buff);
492         free(compressed_buff);
493         free(chunkP);
494         return 13;
495       }
496 
497       /* Calculating input Checksum */
498       crcOriginal = XXH32(orig_buff, benchedSize,0);
499 
500 
501       /* Bench */
502       { int loopNb, nb_loops, chunkNb, cAlgNb, dAlgNb;
503         size_t cSize=0;
504         double ratio=0.;
505 
506         DISPLAY("\r%79s\r", "");
507         DISPLAY(" %s : \n", inFileName);
508 
509         /* Bench Compression Algorithms */
510         for (cAlgNb=0; (cAlgNb <= NB_COMPRESSION_ALGORITHMS) && (g_compressionTest); cAlgNb++) {
511             const char* compressorName;
512             int (*compressionFunction)(const char*, char*, int);
513             void (*initFunction)(void) = NULL;
514             double bestTime = 100000000.;
515 
516             /* filter compressionAlgo only */
517             if ((g_compressionAlgo != ALL_COMPRESSORS) && (g_compressionAlgo != cAlgNb)) continue;
518 
519             /* Init data chunks */
520             {   int i;
521                 size_t remaining = benchedSize;
522                 char* in = orig_buff;
523                 char* out = compressed_buff;
524                 assert(nbChunks >= 1);
525                 for (i=0; i<nbChunks; i++) {
526                     chunkP[i].id = (U32)i;
527                     chunkP[i].origBuffer = in; in += g_chunkSize;
528                     assert(g_chunkSize > 0);
529                     if (remaining > (size_t)g_chunkSize) {
530                         chunkP[i].origSize = g_chunkSize;
531                         remaining -= (size_t)g_chunkSize;
532                     } else {
533                         chunkP[i].origSize = (int)remaining;
534                         remaining = 0;
535                     }
536                     chunkP[i].compressedBuffer = out; out += maxCompressedChunkSize;
537                     chunkP[i].compressedSize = 0;
538                 }
539             }
540 
541             switch(cAlgNb)
542             {
543             case 0 : DISPLAY("Compression functions : \n"); continue;
544             case 1 : compressionFunction = local_LZ4_compress_default_large; compressorName = "LZ4_compress_default"; break;
545             case 2 : compressionFunction = local_LZ4_compress_default_small; compressorName = "LZ4_compress_default(small dst)"; break;
546             case 3 : compressionFunction = local_LZ4_compress_destSize; compressorName = "LZ4_compress_destSize"; break;
547             case 4 : compressionFunction = local_LZ4_compress_fast0; compressorName = "LZ4_compress_fast(0)"; break;
548             case 5 : compressionFunction = local_LZ4_compress_fast1; compressorName = "LZ4_compress_fast(1)"; break;
549             case 6 : compressionFunction = local_LZ4_compress_fast2; compressorName = "LZ4_compress_fast(2)"; break;
550             case 7 : compressionFunction = local_LZ4_compress_fast17; compressorName = "LZ4_compress_fast(17)"; break;
551             case 8 : compressionFunction = local_LZ4_compress_fast_extState0; compressorName = "LZ4_compress_fast_extState(0)"; break;
552             case 9 : compressionFunction = local_LZ4_compress_fast_continue0; initFunction = local_LZ4_createStream; compressorName = "LZ4_compress_fast_continue(0)"; break;
553 
554             case 10: compressionFunction = local_LZ4_compress_HC; compressorName = "LZ4_compress_HC"; break;
555             case 12: compressionFunction = local_LZ4_compress_HC_extStateHC; compressorName = "LZ4_compress_HC_extStateHC"; break;
556             case 14: compressionFunction = local_LZ4_compress_HC_continue; initFunction = local_LZ4_resetStreamHC; compressorName = "LZ4_compress_HC_continue"; break;
557 #ifndef LZ4_DLL_IMPORT
558             case 20: compressionFunction = local_LZ4_compress_forceDict; initFunction = local_LZ4_resetDictT; compressorName = "LZ4_compress_forceDict"; break;
559 #endif
560             case 30: compressionFunction = local_LZ4F_compressFrame; compressorName = "LZ4F_compressFrame";
561                         chunkP[0].origSize = (int)benchedSize; nbChunks=1;
562                         break;
563             case 40: compressionFunction = local_LZ4_saveDict; compressorName = "LZ4_saveDict";
564                         if (chunkP[0].origSize < 8) { DISPLAY(" cannot bench %s with less then 8 bytes \n", compressorName); continue; }
565                         LZ4_loadDict(&LZ4_stream, chunkP[0].origBuffer, chunkP[0].origSize);
566                         break;
567             case 41: compressionFunction = local_LZ4_saveDictHC; compressorName = "LZ4_saveDictHC";
568                         if (chunkP[0].origSize < 8) { DISPLAY(" cannot bench %s with less then 8 bytes \n", compressorName); continue; }
569                         LZ4_loadDictHC(&LZ4_streamHC, chunkP[0].origBuffer, chunkP[0].origSize);
570                         break;
571             default :
572                 continue;   /* unknown ID : just skip */
573             }
574 
575             for (loopNb = 1; loopNb <= g_nbIterations; loopNb++) {
576                 double averageTime;
577                 clock_t clockTime;
578 
579                 PROGRESS("%2i-%-34.34s :%10i ->\r", loopNb, compressorName, (int)benchedSize);
580                 { size_t i; for (i=0; i<benchedSize; i++) compressed_buff[i]=(char)i; }     /* warming up memory */
581 
582                 nb_loops = 0;
583                 clockTime = clock();
584                 while(clock() == clockTime);
585                 clockTime = clock();
586                 while(BMK_GetClockSpan(clockTime) < TIMELOOP) {
587                     if (initFunction!=NULL) initFunction();
588                     for (chunkNb=0; chunkNb<nbChunks; chunkNb++) {
589                         chunkP[chunkNb].compressedSize = compressionFunction(chunkP[chunkNb].origBuffer, chunkP[chunkNb].compressedBuffer, chunkP[chunkNb].origSize);
590                         if (chunkP[chunkNb].compressedSize==0) {
591                             DISPLAY("ERROR ! %s() = 0 !! \n", compressorName);
592                             exit(1);
593                     }   }
594                     nb_loops++;
595                 }
596                 clockTime = BMK_GetClockSpan(clockTime);
597 
598                 nb_loops += !nb_loops;   /* avoid division by zero */
599                 averageTime = ((double)clockTime) / nb_loops / CLOCKS_PER_SEC;
600                 if (averageTime < bestTime) bestTime = averageTime;
601                 cSize=0; for (chunkNb=0; chunkNb<nbChunks; chunkNb++) cSize += (size_t)chunkP[chunkNb].compressedSize;
602                 ratio = (double)cSize/(double)benchedSize*100.;
603                 PROGRESS("%2i-%-34.34s :%10i ->%9i (%5.2f%%),%7.1f MB/s\r", loopNb, compressorName, (int)benchedSize, (int)cSize, ratio, (double)benchedSize / bestTime / 1000000);
604             }
605 
606             if (ratio<100.)
607                 DISPLAY("%2i-%-34.34s :%10i ->%9i (%5.2f%%),%7.1f MB/s\n", cAlgNb, compressorName, (int)benchedSize, (int)cSize, ratio, (double)benchedSize / bestTime / 1000000);
608             else
609                 DISPLAY("%2i-%-34.34s :%10i ->%9i (%5.1f%%),%7.1f MB/s\n", cAlgNb, compressorName, (int)benchedSize, (int)cSize, ratio, (double)benchedSize / bestTime / 100000);
610         }
611 
612         /* Prepare layout for decompression */
613         /* Init data chunks */
614         { int i;
615           size_t remaining = benchedSize;
616           char* in = orig_buff;
617           char* out = compressed_buff;
618 
619           nbChunks = (int) (((int)benchedSize + (g_chunkSize-1))/ g_chunkSize);
620           for (i=0; i<nbChunks; i++) {
621               chunkP[i].id = (U32)i;
622               chunkP[i].origBuffer = in; in += g_chunkSize;
623               if ((int)remaining > g_chunkSize) {
624                   chunkP[i].origSize = g_chunkSize;
625                   remaining -= (size_t)g_chunkSize;
626               } else {
627                   chunkP[i].origSize = (int)remaining;
628                   remaining = 0;
629               }
630               chunkP[i].compressedBuffer = out; out += maxCompressedChunkSize;
631               chunkP[i].compressedSize = 0;
632           }
633         }
634         for (chunkNb=0; chunkNb<nbChunks; chunkNb++) {
635             chunkP[chunkNb].compressedSize = LZ4_compress_default(chunkP[chunkNb].origBuffer, chunkP[chunkNb].compressedBuffer, chunkP[chunkNb].origSize, maxCompressedChunkSize);
636             if (chunkP[chunkNb].compressedSize==0) {
637                 DISPLAY("ERROR ! %s() = 0 !! \n", "LZ4_compress");
638                 exit(1);
639         }   }
640 
641         /* Decompression Algorithms */
642         for (dAlgNb=0; (dAlgNb <= NB_DECOMPRESSION_ALGORITHMS) && g_decompressionTest; dAlgNb++) {
643             const char* dName = NULL;
644             int (*decompressionFunction)(const char*, char*, int, int) = NULL;
645             double bestTime = 100000000.;
646             int checkResult = 1;
647 
648             if ((g_decompressionAlgo != ALL_DECOMPRESSORS) && (g_decompressionAlgo != dAlgNb)) continue;
649 
650             switch(dAlgNb)
651             {
652             case 0: DISPLAY("Decompression functions : \n"); continue;
653             case 1: decompressionFunction = local_LZ4_decompress_fast; dName = "LZ4_decompress_fast"; break;
654             case 2: decompressionFunction = local_LZ4_decompress_fast_usingDict_prefix; dName = "LZ4_decompress_fast_usingDict(prefix)"; break;
655             case 3: decompressionFunction = local_LZ4_decompress_fast_usingExtDict; dName = "LZ4_decompress_fast_using(Ext)Dict"; break;
656             case 4: decompressionFunction = LZ4_decompress_safe; dName = "LZ4_decompress_safe"; break;
657             case 5: decompressionFunction = local_LZ4_decompress_safe_withPrefix64k; dName = "LZ4_decompress_safe_withPrefix64k"; break;
658             case 6: decompressionFunction = local_LZ4_decompress_safe_usingDict; dName = "LZ4_decompress_safe_usingDict"; break;
659             case 7: decompressionFunction = local_LZ4_decompress_safe_partial; dName = "LZ4_decompress_safe_partial"; checkResult = 0; break;
660 #ifndef LZ4_DLL_IMPORT
661             case 8: decompressionFunction = local_LZ4_decompress_safe_forceExtDict; dName = "LZ4_decompress_safe_forceExtDict"; break;
662 #endif
663             case 10:
664             case 11:
665             case 12:
666                 if (dAlgNb == 10) { decompressionFunction = local_LZ4F_decompress; dName = "LZ4F_decompress"; }  /* can be skipped */
667                 if (dAlgNb == 11) { decompressionFunction = local_LZ4F_decompress_followHint; dName = "LZ4F_decompress_followHint"; }  /* can be skipped */
668                 if (dAlgNb == 12) { decompressionFunction = local_LZ4F_decompress_noHint; dName = "LZ4F_decompress_noHint"; }  /* can be skipped */
669                 /* prepare compressed data using frame format */
670                 {   size_t const fcsize = LZ4F_compressFrame(compressed_buff, (size_t)compressedBuffSize, orig_buff, benchedSize, NULL);
671                     assert(!LZ4F_isError(fcsize));
672                     chunkP[0].origSize = (int)benchedSize;
673                     chunkP[0].compressedSize = (int)fcsize;
674                     nbChunks = 1;
675                     break;
676                 }
677             default :
678                 continue;   /* skip if unknown ID */
679             }
680 
681             assert(decompressionFunction != NULL);
682             assert(dName != NULL);
683 
684             { size_t i; for (i=0; i<benchedSize; i++) orig_buff[i]=0; }     /* zeroing source area, for CRC checking */
685 
686             for (loopNb = 1; loopNb <= g_nbIterations; loopNb++) {
687                 double averageTime;
688                 clock_t clockTime;
689                 U32 crcDecoded;
690 
691                 PROGRESS("%2i-%-34.34s :%10i ->\r", loopNb, dName, (int)benchedSize);
692 
693                 nb_loops = 0;
694                 clockTime = clock();
695                 while(clock() == clockTime);
696                 clockTime = clock();
697                 while(BMK_GetClockSpan(clockTime) < TIMELOOP) {
698                     for (chunkNb=0; chunkNb<nbChunks; chunkNb++) {
699                         int const decodedSize = decompressionFunction(chunkP[chunkNb].compressedBuffer, chunkP[chunkNb].origBuffer,
700                                                                       chunkP[chunkNb].compressedSize, chunkP[chunkNb].origSize);
701                         if (chunkP[chunkNb].origSize != decodedSize) {
702                             DISPLAY("ERROR ! %s() == %i != %i !! \n",
703                                     dName, decodedSize, chunkP[chunkNb].origSize);
704                             exit(1);
705                     }   }
706                     nb_loops++;
707                 }
708                 clockTime = BMK_GetClockSpan(clockTime);
709 
710                 nb_loops += !nb_loops;   /* Avoid division by zero */
711                 averageTime = (double)clockTime / nb_loops / CLOCKS_PER_SEC;
712                 if (averageTime < bestTime) bestTime = averageTime;
713 
714                 PROGRESS("%2i-%-34.34s :%10i -> %7.1f MB/s\r", loopNb, dName, (int)benchedSize, (double)benchedSize / bestTime / 1000000);
715 
716                 /* CRC Checking */
717                 crcDecoded = XXH32(orig_buff, benchedSize, 0);
718                 if (checkResult && (crcOriginal!=crcDecoded)) {
719                     DISPLAY("\n!!! WARNING !!! %14s : Invalid Checksum : %x != %x\n",
720                             inFileName, (unsigned)crcOriginal, (unsigned)crcDecoded);
721                     exit(1);
722             }   }
723 
724             DISPLAY("%2i-%-34.34s :%10i -> %7.1f MB/s\n", dAlgNb, dName, (int)benchedSize, (double)benchedSize / bestTime / 1000000);
725         }
726       }
727       free(orig_buff);
728       free(compressed_buff);
729       free(chunkP);
730     }
731 
732     LZ4F_freeDecompressionContext(g_dCtx);
733     if (g_pause) { printf("press enter...\n"); (void)getchar(); }
734 
735     return 0;
736 }
737 
738 
usage(const char * exename)739 static int usage(const char* exename)
740 {
741     DISPLAY( "Usage :\n");
742     DISPLAY( "      %s [arg] file1 file2 ... fileX\n", exename);
743     DISPLAY( "Arguments :\n");
744     DISPLAY( " -c     : compression tests only\n");
745     DISPLAY( " -d     : decompression tests only\n");
746     DISPLAY( " -H/-h  : Help (this text + advanced options)\n");
747     return 0;
748 }
749 
usage_advanced(void)750 static int usage_advanced(void)
751 {
752     DISPLAY( "\nAdvanced options :\n");
753     DISPLAY( " -c#    : test only compression function # [1-%i]\n", NB_COMPRESSION_ALGORITHMS);
754     DISPLAY( " -d#    : test only decompression function # [1-%i]\n", NB_DECOMPRESSION_ALGORITHMS);
755     DISPLAY( " -i#    : iteration loops [1-9](default : %i)\n", NBLOOPS);
756     DISPLAY( " -B#    : Block size [4-7](default : 7)\n");
757     return 0;
758 }
759 
badusage(const char * exename)760 static int badusage(const char* exename)
761 {
762     DISPLAY("Wrong parameters\n");
763     usage(exename);
764     return 0;
765 }
766 
main(int argc,const char ** argv)767 int main(int argc, const char** argv)
768 {
769     int i,
770         filenamesStart=2;
771     const char* exename = argv[0];
772     const char* input_filename=0;
773 
774     // Welcome message
775     DISPLAY(WELCOME_MESSAGE);
776 
777     if (argc<2) { badusage(exename); return 1; }
778 
779     for(i=1; i<argc; i++) {
780         const char* argument = argv[i];
781 
782         if(!argument) continue;   // Protection if argument empty
783         if (!strcmp(argument, "--no-prompt")) {
784             g_noPrompt = 1;
785             continue;
786         }
787 
788         // Decode command (note : aggregated commands are allowed)
789         if (argument[0]=='-') {
790             while (argument[1]!=0) {
791                 argument ++;
792 
793                 switch(argument[0])
794                 {
795                     // Select compression algorithm only
796                 case 'c':
797                     g_decompressionTest = 0;
798                     while ((argument[1]>= '0') && (argument[1]<= '9')) {
799                         g_compressionAlgo *= 10;
800                         g_compressionAlgo += argument[1] - '0';
801                         argument++;
802                     }
803                     break;
804 
805                     // Select decompression algorithm only
806                 case 'd':
807                     g_compressionTest = 0;
808                     while ((argument[1]>= '0') && (argument[1]<= '9')) {
809                         g_decompressionAlgo *= 10;
810                         g_decompressionAlgo += argument[1] - '0';
811                         argument++;
812                     }
813                     break;
814 
815                     // Display help on usage
816                 case 'h' :
817                 case 'H': usage(exename); usage_advanced(); return 0;
818 
819                     // Modify Block Properties
820                 case 'B':
821                     while (argument[1]!=0)
822                     switch(argument[1])
823                     {
824                     case '4':
825                     case '5':
826                     case '6':
827                     case '7':
828                     {   int B = argument[1] - '0';
829                         int S = 1 << (8 + 2*B);
830                         BMK_setBlocksize(S);
831                         argument++;
832                         break;
833                     }
834                     case 'D': argument++; break;
835                     default : goto _exit_blockProperties;
836                     }
837 _exit_blockProperties:
838                     break;
839 
840                     // Modify Nb Iterations
841                 case 'i':
842                     if ((argument[1] >='0') && (argument[1] <='9')) {
843                         int iters = argument[1] - '0';
844                         BMK_setNbIterations(iters);
845                         argument++;
846                     }
847                     break;
848 
849                     // Pause at the end (hidden option)
850                 case 'p': BMK_setPause(); break;
851 
852                     // Unknown command
853                 default : badusage(exename); return 1;
854                 }
855             }
856             continue;
857         }
858 
859         // first provided filename is input
860         if (!input_filename) { input_filename=argument; filenamesStart=i; continue; }
861 
862     }
863 
864     // No input filename ==> Error
865     if(!input_filename) { badusage(exename); return 1; }
866 
867     return fullSpeedBench(argv+filenamesStart, argc-filenamesStart);
868 
869 }
870