#!/usr/local/bin/perl
#
#
# Author: Azat Badretdinov
#
# Usage: new profile, old profile and divide flag
#
# divides new time spent by the routine  by old one if divide flag is not 0
# otherwise substract them from each other
#
# the fields are quite straitforward otherwise....
#
# example: diff_prof slow.pixie.Counts.prof fast.pixie.Counts.prof divide

# compares the differences between two profiles
# sorted according to first profile
# Order: new old
@text1 = `cutout 'Function list, in descending order by exclusive ideal time' vla-vla 1 < $ARGV[0]`;
@text2 = `cutout 'Function list, in descending order by exclusive ideal time' vla-vla 1 < $ARGV[1]`;
$divide=$ARGV[2];
@text1 = grep( /^\s*\[\d+\]\s+/, @text1);
@text2 = grep( /^\s*\[\d+\]\s+/, @text2);

print scalar(@text1),"\n";
foreach $s (@text1)
  {
  ($index,$excl_sec,$excl_per,$cum_per,$cyc,$instr,$calls,$function,$rest)=split(' ',$s,9);
  push(@keys,$function);
  $index{$function}[0]=$index;
  $excl_sec{$function}[0]=$excl_sec;
  $excl_per{$function}[0]=$excl_per;
  $cum_per{$function}[0]=$cum_per;
  $cyc{$function}[0]=$cyc;
  $instr{$function}[0]=$instr;
  $calls{$function}[0]=$calls;
#  print "$function 1\n";
  }
foreach $s (@text2)
  {
  ($index,$excl_sec,$excl_per,$cum_per,$cyc,$instr,$calls,$function,$rest)=split(' ',$s,9);
  $index{$function}[1]=$index;
  $excl_sec{$function}[1]=$excl_sec;
  $excl_per{$function}[1]=$excl_per;
  $cum_per{$function}[1]=$cum_per;
  $cyc{$function}[1]=$cyc;
  $instr{$function}[1]=$instr;
  $calls{$function}[1]=$calls;
#  print "$function 2\n";
  
  }
foreach $function (@keys)
  {
  if($divide)
    {
    $excl_sec=sprintf("%f s / %f s = %f", $excl_sec{$function}[0], $excl_sec{$function}[1], 
       $excl_sec{$function}[0]/($excl_sec{$function}[1]==0.0 ?  1: $excl_sec{$function}[1]) );
    $excl_per=sprintf("%f s / %f s = %f", $excl_per{$function}[0], $excl_per{$function}[1], 
       $excl_per{$function}[0]/($excl_per{$function}[1]==0.0 ? 1: $excl_sec{$function}[1]) );
    }
  else
    {
    $excl_sec=sprintf("%f s - %f s = %f", $excl_sec{$function}[0], $excl_sec{$function}[1], 
       $excl_sec{$function}[0]-($excl_sec{$function}[1]==0.0 ?  0: $excl_sec{$function}[1]) );
    $excl_per=sprintf("%f s - %f s = %f", $excl_per{$function}[0], $excl_per{$function}[1], 
       $excl_per{$function}[0]-($excl_per{$function}[1]==0.0 ? 0: $excl_sec{$function}[1]) );
    }
  $excl_sec=~s/0+ s/ s/g;$excl_sec=~s/0+$//g;
  $excl_per=~s/0+ s/ s/g;$excl_per=~s/0+$//g;
  printf("%8.8s %36.36s %36.36s %15.3f %15.3f %15.3f %s\n" ,
    $index{$function}[0], $excl_sec, $excl_per,
    $cyc  {$function}[0]/($cyc  {$function}[1] || 1), 
    $instr{$function}[0]/($instr{$function}[1] || 1),
    $calls{$function}[0]/($calls{$function}[1] || 1), $function);
  }