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