#!/usr/bin/env perl

my $gmfilelist = `ls *.gmon`;
my $foundopening = 0;
my $foundclosing = 0;
my @missing;
my $missingnext = 0;

my @ticks;
my @funcs;
my $nextfunc = 0;

sub locatebin {
	my ($gmfilename) = @_;
	my @locations = (
		"/lib",
		"/usr/lib",
		"/bin",
		"/usr/bin",
		"/sbin",
		"/usr/sbin",
		"/usr/local/lib",
		"/usr/X11R6/lib",
		"/usr/local/bin",
		"/usr/X11R6/bin",
		"/libexec",
		"/usr/local/libexec",
		"/boot/kernel");

	foreach $loc (@locations) {
		$binfilename = $gmfilename;
		$binfilename =~ s/.gmon//;
		$binfilename = $loc . "/" . $binfilename;
		if (-e $binfilename) {
			return $binfilename;
		}
	}
	return "";
}

foreach $gmfilename (split(/\s+/, $gmfilelist)) {
	my $binfilename = locatebin($gmfilename);

	if ($binfilename eq "") {
		@missing[$missingnext++] = $gmfilename;
		next;
	}
	system("gprof $binfilename $gmfilename > gprof.out 2>/dev/null");
	if (!open(GPROF, "gprof.out")) {
		printf("couldn't open gprof output\n");
		next;
	}
	while ($line = <GPROF>) {
		# time, seconds, self seconds, calls, ms/call, tot ms/call, name
		if ($line =~ /([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9]+)\s+([0-9.]*)%\s+([0-9.]*)\s+([^\s]*)/) {
			#printf("found %s\n", $line);
			my $selfticks = $3;
			my $funcname = $7;
			@ticks[$nextfunc] = $selfticks;
			@funcs[$nextfunc] = "$binfilename:$funcname";
			$nextfunc++;
		}
	}
}

foreach $i (@missing) {
	printf("didn't find %s\n", $i);
}

my $totalticks = 0;
for (my $i = 0; $i < $nextfunc; $i++) {
	$totalticks += @ticks[$i];
}
for (my $i = 0; $i < $nextfunc; $i++) {
	my $truncfunc = @funcs[$i];
	$truncfunc =~ s/.*\/(.*)/$1/;
	printf("%10s (%2.2f%) %s\n", @ticks[$i], @ticks[$i] / $totalticks * 100,
	    $truncfunc);
}
