uncoverable: comments
[Text-CSV_XS.git] / examples / speed.pl
1 #!/usr/bin/perl -w
2
3 # speed.pl: compare different versions of Text-CSV* modules
4 # (m)'08 [07 Apr 2008] Copyright H.M.Brand 2007-2014
5
6 require 5.006001;
7 use strict;
8
9 use IO::Handle;
10 use Text::CSV_XS;
11 use Benchmark "timethese";
12 eval { Benchmark->import (":hireswallclock"); };
13
14 our $csv = Text::CSV_XS->new ({ eol => "\n" });
15
16 my $duration = int (shift || 2);
17 my @fields = (
18 "Holmes", "Sherlock",
19 "Baker street", 221, "B",
20 72555, "London", "NW1 6XE",
21 "United Kingdom",
22 "+44 7123 84567",
23 "sherlock\@holmes,co.uk");
24 our @fields1 = (@fields) x 1;
25 our @fields10 = (@fields) x 10;
26 our @fields100 = (@fields) x 100;
27
28 $csv->combine (@fields1 ); our $str1 = $csv->string;
29 $csv->combine (@fields10 ); our $str10 = $csv->string;
30 $csv->combine (@fields100); our $str100 = $csv->string;
31
32 timethese (-1.5,{
33
34 "combine 1" => q{ $csv->combine (@fields1 ) },
35 "combine 10" => q{ $csv->combine (@fields10 ) },
36 "combine 100" => q{ $csv->combine (@fields100) },
37
38 "parse 1" => q{ $csv->parse ($str1 ) },
39 "parse 10" => q{ $csv->parse ($str10 ) },
40 "parse 100" => q{ $csv->parse ($str100 ) },
41
42 });
43
44 sub max { $_[0] >= $_[1] ? $_[0] : $_[1] }
45 my $line_count = max (200_000, 20_000 * $duration);
46
47 our $io;
48 my $mem = "";
49 my $bigfile = "_file.csv";
50 if ($] >= 5.010) {
51 eval "use Sys::MemInfo qw( freemem );";
52 unless ($@) {
53 my $need = $line_count * (1 + length $str10);
54 if (freemem () > $need) {
55 $mem = "";
56 open $io, ">", \$mem;
57 }
58 }
59 }
60 $io or open $io, ">", $bigfile;
61
62 $csv->print ($io, \@fields10) or die "Cannot print ()\n";
63 timethese ($line_count, { "print io" => q{ $csv->print ($io, \@fields10) }});
64 close $io;
65 my $l = $mem ? length ($mem) : -s $bigfile;
66 $l or die "Buffer/file is empty!\n";
67 my @f = @fields10;
68 $csv->can ("bind_columns") and $csv->bind_columns (\(@f));
69 open $io, "<", ($mem ? \$mem : $bigfile);
70 timethese ($line_count, { "getline io" => q{ my $ref = $csv->getline ($io) }});
71 close $io;
72 print "Data was $l bytes long, line length ", length ($str10), "\n";
73 $mem or unlink $bigfile;
74
75 __END__
76 # The examples from the docs
77
78 { $csv = Text::CSV_XS->new ({ keep_meta_info => 1, binary => 1 });
79
80 my $sample_input_string =
81 qq{"I said, ""Hi!""",Yes,"",2.34,,"1.09","\x{20ac}",};
82 if ($csv->parse ($sample_input_string)) {
83 my @field = $csv->fields;
84 foreach my $col (0 .. $#field) {
85 my $quo = $csv->is_quoted ($col) ? $csv->{quote_char} : "";
86 printf "%2d: %s%s%s\n", $col, $quo, $field[$col], $quo;
87 }
88 }
89 else {
90 my $err = $csv->error_input;
91 print "parse () failed on argument: ", $err, "\n";
92 }
93 }