blib/lib/Parallel/Subs.pm

filter: Statementstmt 71.3% 92 / 129 Branchbran 41.3% 19 / 46 Conditioncond 31.2% 5 / 16 MC/DCmcdc 10.0% 1 / 10 Subroutinesub 81.2% 13 / 16 Podpod 100% 7 / 7 totaltotal 61.1% 137 / 224 CC 33 SCAR 31.6
CC
33
Cov
61%
wait_for_all_optimized
90.0
wait_for_all
19.7
_pfork
8.2
CRAP 23.5
↑ Summary
1 package Parallel::Subs;
2 44 $Parallel::Subs::VERSION = '0.002';
3 44 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 44 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 44 ▶use Parallel::ForkManager;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 44 ▶use Sys::Info;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # ABSTRACT: Simple way to run subs in parallel and process their return value in perl
10  
11  
12 sub new {
13 102 ▶ my ( $class, %opts ) = @_;
Subroutine new: called CC=1 SCAR=0.0
Pod documented
14  
15 102 my $self = bless {}, __PACKAGE__;
16  
17 102 $self->_init(%opts);
18  
19 102 return $self;
20 }
21  
22 sub _init {
23 102 ▶ my ( $self, %opts ) = @_;
Subroutine _init: called CC=1 SCAR=0.1
24  
25 102 $self->_pfork(%opts);
26 102 $self->{result} = {};
27 $self->{pfork}->run_on_finish(
28 sub {
29 243 ▶ my ( $pid, $exit, $id, $exit_signal, $core_dump, $data ) = @_;
Subroutine __ANON__: called CC=3 SCAR=12.5
30 243 ▶ die "Failed to process on one job, stop here !"
Branch: 1 branch
BranchTrueFalseTotal
if $exit or $exit_signal 0 243 243
Condition33%1/3
$exit or $exit_signal
l!l&&r!l&&!r
00243
MC/DC0%0/2
$exit or $exit_signal
$exit $exit_signal
Truth table33%1/3
A or B
A= $exitB= $exit_signal
ABresult
1X1
011
000
31 if $exit || $exit_signal;
32 243 $self->{result}->{$id} = $data->{result};
33 }
34 102 );
35 102 $self->{jobs} = [];
36 102 $self->{callbacks} = [];
37  
38 102 return $self;
39 }
40  
41 sub _pfork {
42 102 ▶ my ( $self, %opts ) = @_;
Subroutine _pfork: called CC=8 SCAR=21.0
43  
44 102 my $cpu;
45 102 ▶ if ( defined $opts{max_process} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{'max_process'}) { } 19 83 102
46 19 $cpu = $opts{max_process};
47 }
48 else {
49 83 ▶ my $factor = $opts{max_process_per_cpu} || 1;
Condition100%2/2
$opts{'max_process_per_cpu'} || 1
l!l
1568
MC/DC100%1/1
$opts{'max_process_per_cpu'} || 1
$opts{'max_process_per_cpu'}
Truth table100%2/2
A
A= $opts{'max_process_per_cpu'}
Aresult
11
00
50 83 eval { $cpu = Sys::Info->new()->device('CPU')->count() * $factor; };
51 }
52 102 ▶ if ( defined $opts{max_memory} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"max_memory"}) 11 91 102
53 11 my $free_mem;
54 11 eval {
55 11 require Sys::Statistics::Linux::MemStats;
56 11 $free_mem = Sys::Statistics::Linux::MemStats->new->get->{realfree};
57 };
58 11 my $max_mem = $opts{max_memory} * 1024; # 1024 **2 = 1 GO => expr in Kb
59 11 my $cpu_for_mem;
60 11 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 11 11
61  
62 #warn "Cannot guess amount of available free memory need Sys::Statistics::Linux::MemStats\n";
63 0 $cpu_for_mem = 2;
64 }
65 else {
66 11 $cpu_for_mem = int( $free_mem / $max_mem );
67 }
68  
69 # min
70 11 ▶ $cpu = ( $cpu_for_mem < $cpu ) ? $cpu_for_mem : $cpu;
Branch: 1 branch
BranchTrueFalseTotal
$cpu_for_mem < $cpu ? : 0 11 11
71 }
72 102 ▶ $cpu ||= 1;
Condition50%1/2
$cpu ||= 1
l!l
1020
MC/DC0%0/1
$cpu ||= 1
$cpu
Truth table50%1/2
A
A= $cpu
Aresult
11
00
73  
74 102 $self->{cpu} = $cpu;
75  
76 # we could also set a minimum amount of required memory
77 102 $self->{pfork} = Parallel::ForkManager->new( int($cpu) );
78 $self->{pfork}->set_waitpid_blocking_sleep(0)
79 102 ▶ unless $opts{waitpid_blocking_sleep};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts{"waitpid_blocking_sleep"} 102 0 102
80  
81 102 return $self;
82 }
83  
84  
85 sub add {
86 435 ▶ my ( $self, $code, $test ) = @_;
Subroutine add: called CC=3 SCAR=11.3
Pod documented
87  
88 435 ▶ return unless $code && ref $code eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless $code and ref $code eq "CODE" 0 435 435
Condition33%1/3
$code and ref $code eq "CODE"
!ll&&!rl&&r
00435
MC/DC0%0/2
$code and ref $code eq "CODE"
$code ref $code eq "CODE"
Truth table33%1/3
A and B
A= $codeB= ref $code eq "CODE"
ABresult
0X0
100
111
89 push(
90 435 @{ $self->{jobs} },
91 435 { name => ( scalar( @{ $self->{jobs} } ) + 1 ), code => $code }
92 );
93 435 push( @{ $self->{callbacks} }, $test );
94  
95 435 return $self;
96 }
97  
98  
99 sub total_jobs {
100 9 ▶ my ($self) = @_;
Subroutine total_jobs: called CC=1 SCAR=0.0
Pod documented
101  
102 9 return scalar @{ $self->{jobs} };
103 }
104  
105  
106 sub wait_for_all_optimized {
107 0 ▶ my ($self) = @_;
Subroutine wait_for_all_optimized: not called CC=9 SCAR=45.0
Pod documented
108  
109 0 ▶ return $self unless $self->total_jobs;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->total_jobs 0 0 0
110 0 my @original_jobs = @{ $self->{jobs} };
111  
112 # callback not supported for now
113 0 ▶ if ( scalar @{ $self->{callbacks} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$self->{"callbacks"};}) 0 0 0
114 warn "Callback not supported in this mode for now.\n"
115 0 ▶ if grep { defined $_ } @{ $self->{callbacks} };
Branch: 1 branch
BranchTrueFalseTotal
if grep {defined $_;} @{$$self{"callbacks"};} 0 0 0
116 0 $self->{callbacks} = [];
117 }
118  
119 0 ▶ my $cpu = $self->{cpu} or die;
Branch: 1 branch
BranchTrueFalseTotal
my $cpu = $self->{"cpu"} or die 0 0 0
120 0 my $jobs_per_cpu = int( scalar @original_jobs / $cpu );
121 0 ▶ ++$jobs_per_cpu if scalar @original_jobs % $cpu || !$jobs_per_cpu;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @original_jobs % $cpu or not $jobs_per_cpu 0 0 0
Condition0%0/3
scalar @original_jobs % $cpu or not $jobs_per_cpu
l!l&&r!l&&!r
000
MC/DC0%0/2
scalar @original_jobs % $cpu or not $jobs_per_cpu
scalar @original_jobs % $cpu not $jobs_per_cpu
Truth table0%0/3
A or not(B)
A= scalar @original_jobs % $cpuB= not $jobs_per_cpu
ABresult
1X1
011
000
122  
123 0 my @new_jobs;
124  
125 my $generate_sub = sub {
126 0 ▶ my ( $from, $to ) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
127  
128 return sub {
129  
130 #print "subprocess from $from to $to\n";
131 0 ▶ for ( my $i = $from ; $i <= $to ; ++$i ) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if ($i <= $to) 0 0 0
132  
133 #print "running job $i\n";
134 0 $original_jobs[$i]->{code}->();
135 }
136 0 return;
137 0 };
138 0 };
139  
140 0 my ( $from, $to ) = ( 0, 0 );
141 0 foreach my $id ( 1 .. $cpu ) {
142 0 $to = $from + $jobs_per_cpu - 1;
143 0 ▶ $to = scalar(@original_jobs) - 1 if $to >= scalar(@original_jobs);
Branch: 1 branch
BranchTrueFalseTotal
if $to >= scalar @original_jobs 0 0 0
144  
145 #print "FROM $from - TO $to\n";
146 0 my $sub = $generate_sub->( $from, $to );
147  
148 0 push @new_jobs, { name => $id, code => $sub };
149 0 $from = $to + 1;
150 }
151  
152 0 $self->{jobs} = \@new_jobs;
153  
154 0 return $self->wait_for_all();
155 }
156  
157  
158 sub run {
159 102 ▶ my ($self) = @_;
Subroutine run: called CC=4 SCAR=13.9
Pod documented
160  
161 102 ▶ return unless scalar @{ $self->{jobs} };
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @{$self->{"jobs"};} 0 102 102
162 102 my $pfm = $self->{pfork};
163 102 for my $job ( @{ $self->{jobs} } ) {
164 356 ▶ $pfm->start( $job->{name} ) and next;
Branch: 1 branch
BranchTrueFalseTotal
$pfm->start($job->{"name"}) and next 316 40 356
165 40 my $job_result = $job->{code}();
166  
167 # can be used to stop on first error
168 40 my $job_error = 0;
169 40 $pfm->finish( $job_error, { result => $job_result } );
170 }
171  
172 # wait for all jobs
173 62 $pfm->wait_all_children;
174  
175 62 return $self->{result};
176 }
177  
178  
179 sub wait_for_all {
180 27 ▶ my ($self) = @_;
Subroutine wait_for_all: called CC=10 SCAR=29.8
Pod documented
181  
182 # run callbacks
183 27 ▶ die "Cannot run callbacks" unless $self->run();
Branch: 1 branch
BranchTrueFalseTotal
unless $self->run 0 9 9
184  
185 9 ▶ return $self unless $self->total_jobs;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->total_jobs 0 9 9
186 9 my $c = 0;
187  
188 9 my $results = $self->results();
189  
190 9 foreach my $callback ( @{ $self->{callbacks} } ) {
191 23 ▶ next unless $callback;
Branch: 1 branch
BranchTrueFalseTotal
unless $callback 6 17 23
192 17 ▶ die "cannot find result for #${c}" unless exists $results->[$c];
Branch: 1 branch
BranchTrueFalseTotal
unless exists $results->[$c] 0 17 17
193 17 my $res = $results->[ $c++ ];
194  
195 17 ▶ if ( ref $callback eq 'HASH' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $callback eq 'HASH') { } 0 17 17
elsif (ref $callback eq 'CODE') { } 17 0 17
196  
197 # internal mechanism
198 return
199 0 ▶ unless defined $callback->{test} && defined $callback->{args};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $callback->{"test"} and defined $callback->{"args"} 0 0 0
Condition0%0/3
defined $callback->{"test"} and defined $callback->{"args"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $callback->{"test"} and defined $callback->{"args"}
defined $callback->{"test"} defined $callback->{"args"}
Truth table0%0/3
A and B
A= defined $callback->{"test"}B= defined $callback->{"args"}
ABresult
0X0
100
111
200  
201 0 my @args = ( $res, @{ $callback->{args} } );
202 0 my $t = $callback->{test};
203 0 my $str = join( ', ', map { "\$args[$_]" } ( 0 .. $#args ) );
204 0 eval "$t(" . $str . ")";
205 }
206 elsif ( ref $callback eq 'CODE' ) {
207  
208 # execute user function
209 17 $callback->($res);
210 }
211  
212 }
213  
214 9 return $self;
215 }
216  
217  
218 sub results {
219 62 ▶ my ($self) = @_;
Subroutine results: called CC=1 SCAR=0.0
Pod documented
220  
221 my @sorted =
222 237 map { $self->{result}{$_} }
223 62 sort { int($a) <=> int($b) } keys %{ $self->{result} };
224 62 return \@sorted;
225 }
226  
227 44 1;
228  
229 __END__
230  
231 =pod
232  
233 =encoding UTF-8
234  
235 =head1 NAME
236  
237 Parallel::Subs - Simple way to run subs in parallel and process their return value in perl
238  
239 =head1 VERSION
240  
241 version 0.002
242  
243 =head1 DESCRIPTION
244  
245 Parallel::Subs is a simple object interface used to launch test in parallel.
246 It uses Parallel::ForkManager to launch subs in parallel and get the results.
247  
248 =head1 NAME
249 Parallel::Subs - simple object interface to launch subs in parallel
250 and process their return values.
251  
252 =head1 Usage
253  
254 You could also use the result returned by the function run in custom child process
255 from the main process by providing a second optional sub to process the results
256  
257 =head2 The basics
258  
259 use Parallel::Subs;
260  
261 my $p = Parallel::Subs->new();
262 # or Parallel::Subs->new( max_process => N )
263 # or Parallel::Subs->new( max_process_per_cpu => P )
264 # or Parallel::Subs->new( max_memory => M );
265  
266 # add a first sub which will be launched by its own kid
267 $p->add(
268 sub { # will be launched in parallel
269 # any code that take time to execute can go there
270 print "Hello from kid $$\n";
271 }
272 );
273 # add a second sub
274 $p->add(
275 sub { print "Hello from kid $$\n" }
276 )
277 $p->add( \&do_something );
278  
279 # Trigger all the subs to run in parallel using a limited number of process
280 $p->wait_for_all();
281  
282 print qq[This is done.\n];
283  
284 =head2 Chaining the subs
285  
286 You can also chain the 'add', or even the 'wait_for_all',
287 which can make your code easier to read.
288  
289 use Parallel::Subs;
290  
291 my $p = Parallel::Subs->new()
292 ->add( sub{ print "Hello from kid $$\n"; sleep 5; } )
293 ->add( sub{ print "Hello from kid $$\n"; sleep 4; } )
294 ->add( sub{ print "Hello from kid $$\n"; sleep 3; } )
295 ->add( sub{ print "Hello from kid $$\n"; sleep 2; } )
296 ->add( sub{ print "Hello from kid $$\n"; sleep 1; } )
297 ->add( sub{ print "Hello from kid $$\n" } )
298 ->wait_for_all();
299 # or ->wait_for_all_optimized(); # beta - group jobs and run one single fork per/cpu
300
301 print qq[This is done.\n];
302  
303 =head2 Run subs in parallel and use their return values
304  
305 use Parallel::Subs;
306  
307 my $sum;
308  
309 sub work_to_do {
310 my ( $a, $b ) = @_;
311 return sub {
312 note "Running in parallel from process $$";
313 # need some time to execute...
314 # return 42;
315 # return { value => 42 };
316 # return [ 1..9 ];
317 return $a * $b;
318 }
319 }
320  
321 sub read_result {
322 my $result = shift;
323  
324 $sum += $result;
325 }
326  
327 my $p = Parallel::Subs->new();
328 $p->add(
329 sub {
330 my $time = int( rand(2) );
331 sleep($time);
332 return { number => 1, time => $time };
333 },
334 sub {
335 # run from the main process once the kid process has finished its work
336 # to access return values from previous sub
337 my $result = shift;
338 $sum += $result->{number};
339  
340 return;
341 }
342 )->add( work_to_do( 1, 2 ), \&read_result )
343 ->add( work_to_do( 3, 4 ), \&read_result )
344 ->add( work_to_do( 5, 6 ), \&read_result )
345 ->add( work_to_do( 7, 8 ), \&read_result )
346 ->add( work_to_do( 9, 10 ), \&read_result );
347  
348 $p->wait_for_all();
349  
350 =head1 METHODS
351  
352 =head2 new
353  
354 Create a new Parallel::Subs object.
355  
356 By default it will use the number of cores you have as a maximum limit of parallelized job,
357 but you can control this value with two options :
358  
359 - max_process : set the maximum process to this value
360  
361 - max_process_per_cpu : set the maximum process per cpu, this value
362 will be multiplied by the number of cpu ( core ) avaiable on your server
363  
364 - max_memory : in MB per job. Will use the minimum between #cpu and total memory available / max_memory
365  
366 my $p = Parallel::Subs->new()
367 or Parallel::Subs->new( max_process => N )
368 or Parallel::Subs->new( max_process_per_cpu => P )
369 or Parallel::Subs->new( max_memory => M );
370  
371 =head2 $p->add($code, [$callback])
372  
373 You can add some sub to be run in parallel.
374  
375 $p->add( sub { 1 } );
376 $p->add( sub { return { 1..6 } }, sub { my $result = shift; ... } );
377  
378 =head2 $p->total_jobs
379  
380 return the total number of jobs
381  
382 =head2 $p->wait_for_all_optimized
383  
384 similar to wait_for_all but the goal is to reduce the number of fork
385 by grouping tasks together to be run by the same process
386  
387 For now this does not support callback. This is still in beta testing.
388  
389 =head2 $p->run
390  
391 will run and wait for all jobs added
392 you do not need to use this method except if you prefer to add jobs yourself and manipulate the results
393  
394 =head2 $p->wait_for_all
395  
396 no process will be executed until you call this function
397 which will then trigger parallel jobs and wait for all of them to finish
398  
399 =head2 $p->results
400  
401 get an array of results, in the same order of jobs
402  
403 =head1 AUTHOR
404  
405 Nicolas R <atoomic@cpan.org>
406  
407 =head1 COPYRIGHT AND LICENSE
408  
409 This software is copyright (c) 2018 by Nicolas R.
410  
411 This is free software; you can redistribute it and/or modify it under
412 the same terms as the Perl 5 programming language system itself.
413  
414 =cut
↑ Summary