libtremor: merge upstream revision 17520 and 17521 tweaking some of the recently...
[maemo-rb.git] / tools / multigcc.pl
blob9be9978bd4897870d83a1a839c09c4c75fe31d2b
1 #!/usr/bin/perl
2 use Switch;
3 use List::Util 'shuffle'; # standard from Perl 5.8 and later
5 my $tempfile = "multigcc.out";
6 my @params;
7 my @files;
8 my $list = \@params;
10 # parse command line arguments
11 for my $a (@ARGV) {
12 if ($a eq "--") {
13 $list = \@files;
14 next;
17 push @{$list}, $a;
20 exit if (not @files);
22 my $command = join " ", @params;
24 # shuffle the file list to spread the load as evenly as we can
25 @files = shuffle(@files);
27 # count number of cores
28 my $cores;
29 switch($^O) {
30 case "darwin" {
31 chomp($cores = `sysctl -n hw.ncpu`);
32 $cores = 1 if ($?);
34 case "solaris" {
35 $cores = scalar grep /on-line/i, `psrinfo`;
36 $cores = 1 if ($?);
38 else {
39 if (open CPUINFO, "</proc/cpuinfo") {
40 $cores = scalar grep /^processor/i, <CPUINFO>;
41 close CPUINFO;
43 else {
44 $cores = 1;
49 # fork children
50 my @pids;
51 my $slice = int((scalar @files + $cores) / $cores);
53 # reset $cores to 0 so we can count the number of actually used cores
54 $cores=0;
56 for (my $i=0;$i<scalar @files;$i += $slice)
58 my $pid = fork;
59 if ($pid)
61 # mother
62 $pids[$cores++] = $pid;
64 else
66 # get my slice of the files
67 my @list = @files[$i .. $i + $slice - 1];
69 # run command
70 system("$command @list > $tempfile.$$");
72 exit;
76 for my $i (0 .. $cores - 1)
78 # wait for child to complete
79 waitpid $pids[$i], 0;
81 # read & print result
82 if (open F, "<$tempfile.$pids[$i]")
84 print <F>;
85 close F;
86 unlink "$tempfile.$pids[$i]";