Increase test run-time for speed
[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 qw(:all :hireswallclock);
12
13 our $csv = Text::CSV_XS->new ({ eol => "\n" });
14
15 my $duration = int (shift || 2);
16 our @fields1 = (
17 "Wiedmann", "Jochen",
18 "Am Eisteich 9",
19 "72555 Metzingen",
20 "Germany",
21 "+49 7123 14881",
22 "joe\@ispsoft,de");
23 our @fields10 = (@fields1) x 10;
24 our @fields100 = (@fields1) x 100;
25
26 $csv->combine (@fields1 ); our $str1 = $csv->string;
27 $csv->combine (@fields10 ); our $str10 = $csv->string;
28 $csv->combine (@fields100); our $str100 = $csv->string;
29
30 timethese (-1.5,{
31
32 "combine 1" => q{ $csv->combine (@fields1 ) },
33 "combine 10" => q{ $csv->combine (@fields10 ) },
34 "combine 100" => q{ $csv->combine (@fields100) },
35
36 "parse 1" => q{ $csv->parse ($str1 ) },
37 "parse 10" => q{ $csv->parse ($str10 ) },
38 "parse 100" => q{ $csv->parse ($str100 ) },
39
40 });
41
42 sub max { $_[0] >= $_[1] ? $_[0] : $_[1] }
43 my $line_count = max (200_000, 20_000 * $duration);
44
45 our $io;
46 my $mem = "";
47 my $bigfile = "_file.csv";
48 if ($] >= 5.010) {
49 eval "use Sys::MemInfo qw( freemem );";
50 unless ($@) {
51 my $need = $line_count * (1 + length $str10);
52 if (freemem () > $need) {
53 $mem = "";
54 open $io, ">", \$mem;
55 }
56 }
57 }
58 $io or open $io, ">", $bigfile;
59
60 $csv->print ($io, \@fields10) or die "Cannot print ()\n";
61 timethese ($line_count, { "print io" => q{ $csv->print ($io, \@fields10) }});
62 close $io;
63 my $l = $mem ? length ($mem) : -s $bigfile;
64 $l or die "Buffer/file is empty!\n";
65 my @f = @fields10;
66 $csv->can ("bind_columns") and $csv->bind_columns (\(@f));
67 open $io, "<", ($mem ? \$mem : $bigfile);
68 timethese ($line_count, { "getline io" => q{ my $ref = $csv->getline ($io) }});
69 close $io;
70 print "Data was $l bytes long, line length ", length ($str10), "\n";
71 $mem or unlink $bigfile;
72
73 __END__
74 # The examples from the docs
75
76 { $csv = Text::CSV_XS->new ({ keep_meta_info => 1, binary => 1 });
77
78 my $sample_input_string =
79 qq{"I said, ""Hi!""",Yes,"",2.34,,"1.09","\x{20ac}",};
80 if ($csv->parse ($sample_input_string)) {
81 my @field = $csv->fields;
82 foreach my $col (0 .. $#field) {
83 my $quo = $csv->is_quoted ($col) ? $csv->{quote_char} : "";
84 printf "%2d: %s%s%s\n", $col, $quo, $field[$col], $quo;
85 }
86 }
87 else {
88 my $err = $csv->error_input;
89 print "parse () failed on argument: ", $err, "\n";
90 }
91 }