45eed8e3dff125d2ea7463335b0e738904195bc2
[io-compress-brotli.git] / bin / bro-perl
1 #!perl
2
3 use warnings;
4 use strict;
5 use 5.014;
6
7 use bytes ();
8
9 use File::Slurp;
10 use Getopt::Long;
11 use Time::HiRes qw/ gettimeofday tv_interval /;
12
13 use IO::Compress::Brotli;
14 use IO::Uncompress::Brotli;
15
16 GetOptions(
17 'c|custom-dictionary=s' => \(my $DICTIONARY),
18 'd|decompress' => \(my $DECOMPRESS),
19 'f|force' => \(my $FORCE),
20 'h|help' => \(my $HELP),
21 'i|input=s' => \(my $INPUT),
22 'o|output=s' => \(my $OUTPUT),
23 'q|quality=i' => \(my $QUALITY = 11),
24 'r|repeat=i' => \(my $REPEAT = 1),
25 's|stream=i' => \(my $STREAM),
26 'v|verbose' => \(my $VERBOSE),
27 'w|window=i' => \(my $WINDOW = 22),
28 );
29
30 if( $HELP ) {
31 say "Usage: $0 [--force] [--quality n] [--decompress] [--input filename] [--output filename]".
32 " [--repeat iters] [--verbose] [--window n] [--custom-dictionary filename] [--stream size]";
33 exit 1;
34 }
35
36 if( $REPEAT > 1 && !($INPUT && $OUTPUT) ) {
37 say "You can only run a benchmark on files specifying --input and --output";
38 exit 1;
39 }
40
41 my $t0 = [gettimeofday];
42 my $total_size = 0;
43 my ($encoded, $decoded);
44
45 for ( 1..$REPEAT ) {
46 my $ifh;
47 if( $INPUT ) {
48 open $ifh, "<", $INPUT
49 or die "Cannot open input file $INPUT.\n";
50 }
51 $ifh //= \*STDIN;
52 binmode $ifh;
53
54 my $ofh;
55 if( $OUTPUT ) {
56 die "Output file exists\n"
57 if( -e $OUTPUT && $REPEAT == 1 && !$FORCE );
58 open $ofh, ">", $OUTPUT
59 or die "Cannot open output file $OUTPUT.\n";
60 }
61 $ofh //= \*STDOUT;
62 binmode $ofh;
63
64 if( $DECOMPRESS ) {
65 if( $STREAM ) {
66 my $bro = IO::Uncompress::Brotli->create();
67 while( read $ifh, (my $buf), $STREAM ) {
68 $decoded = $bro->decompress($buf);
69 $total_size += bytes::length( $decoded );
70 print $ofh $decoded;
71 }
72 }
73 else {
74 $encoded = read_file( $ifh );
75 $decoded = unbro( $encoded );
76 $total_size += bytes::length( $decoded );
77 write_file( $ofh, $decoded );
78 }
79 }
80 else {
81 if( $STREAM ) {
82 my $bro = IO::Compress::Brotli->create();
83 $bro->quality( $QUALITY );
84 $bro->window( $WINDOW );
85 while( read $ifh, (my $buf), $STREAM ) {
86 $encoded = $bro->compress($buf);
87 $total_size += bytes::length( $buf );
88 print $ofh $encoded;
89 }
90 $encoded = $bro->finish();
91 print $ofh $encoded;
92 }
93 else {
94 my $decoded = read_file( $ifh );
95 my $encoded = bro( $decoded, $QUALITY, $WINDOW );
96 $total_size += bytes::length( $decoded );
97 write_file( $ofh, $encoded );
98 }
99 }
100 }
101
102 if( $VERBOSE ) {
103 my $elapsed = tv_interval ( $t0 );
104 say "Ran $REPEAT iterations in a total of $elapsed seconds";
105 say sprintf(
106 "Brotli %s speed: %.6f MB/s",
107 ( $DECOMPRESS ? "decompression" : "compression" ),
108 $total_size / 1024 / 1024 / $elapsed
109 );
110 }
This page took 0.023082 seconds and 3 git commands to generate.