Fixed buggy array slicing.
[kugel-rb.git] / tools / multigcc.pl
blob9a43bdb31f1fb322f4891725d8d78b7871551e8b
1 #!/usr/bin/perl
2 use List::Util 'shuffle'; # standard from Perl 5.8 and later
4 my $tempfile = "multigcc.out";
5 my @params;
6 my @files;
7 my $list = \@params;
9 # parse command line arguments
10 for my $a (@ARGV) {
11 if ($a eq "--") {
12 $list = \@files;
13 next;
16 push @{$list}, $a;
19 my $command = join " ", @params;
21 # shuffle the file list to spread the load as evenly as we can
22 @files = shuffle(@files);
24 # count number of cores
25 my $cores = 1;
26 if (open CPUINFO, "</proc/cpuinfo") {
27 $cores = scalar grep /^processor/i, <CPUINFO>;
28 close CPUINFO;
31 # don't run empty children
32 if (scalar @files < $cores)
34 $cores = 1;
37 # fork children
38 my @pids;
39 my $slice = int((scalar @files + $cores) / $cores);
40 for my $i (0 .. $cores-1)
42 my $pid = fork;
43 if ($pid)
45 # mother
46 $pids[$i] = $pid;
48 else
50 # get my slice of the files
51 my @list = @files[$i * $slice .. $i * $slice + $slice - 1];
53 # run command
54 system("$command @list > $tempfile.$$");
56 exit;
60 for my $i (0 .. $cores - 1)
62 # wait for child to complete
63 waitpid $pids[$i], 0;
65 # read & print result
66 if (open F, "<$tempfile.$pids[$i]")
68 print <F>;
69 close F;
70 unlink "$tempfile.$pids[$i]";