#!/usr/bin/perl

use strict;
use warnings;
use Benchmark qw( cmpthese );
use Mac::Processes;
use MacPerl 'DoAppleScript';

# Take the app name from the command-lines; use iTunes by default
# if none is specified.
my $name = shift || 'iTunes';

cmpthese 1000, {
	osascript	    => sub { osascript($name)      },
	mac_processes	=> sub { mac_processes($name)  },
	do_applescript	=> sub { do_applescript($name) },
	ps_grep			=> sub { ps_grep($name) },
};


## Uncomment the following lines (and comment out the cmpthese
## test above) to just run these routines once.

# print "osascript:      ", osascript($name),      "\n";
# print "Mac::Processes: ", mac_processes($name),  "\n";
# print "DoAppleScript:  ", do_applescript($name), "\n";
# print "ps:             ", ps_grep($name),        "\n";


sub osascript {
	my $app = shift;
	$app =~ s{\\}{\\\\}g;
	$app =~ s{"}{\\"}g;
	$app =~ s{'}{'\\''}g;
	my $applescript = qq{ 'tell application "System Events" to count } . 
			qq{ (every process whose name is "$app")' };
	my $running = qx( osascript -e $applescript );
	chomp $running;
	return $running;
}


sub mac_processes {
	my $app = shift;
	my $running = 0;
	
	PROCESS_LIST:
	while ( my ($psn, $psi) = each(%Process) ) {
		if ($psi->processName eq $app) {
			$running = 1;
			last PROCESS_LIST;
		}
	}
	
	return $running;
}

sub do_applescript {
	my $app = shift;
	$app =~ s{\\}{\\\\}g;
	$app =~ s{"}{\\"}g;
# 	$app =~ s{'}{'\\''}g;
	my $applescript = qq{ tell application "System Events" to count } .
			qq{ (every process whose name is "$app") };
	my $running = DoAppleScript($applescript);
	chomp $running;
	return $running;
}

sub ps_grep {
	my $app = quotemeta shift;
	my $running = qx( ps -xc -o command | egrep -c "^$app\$" );
	chomp $running;
	return $running;
}

__END__

Sample results:

# iTunes is not running
$ ./running-app-test.pl 
                Rate  mac_processes        ps_grep      osascript do_applescript
mac_processes  121/s             --           -55%           -58%           -63%
ps_grep        267/s           120%             --            -7%           -20%
osascript      287/s           136%             7%             --           -14%
do_applescript 332/s           174%            24%            16%             --


# iTunes is running
$ ./running-app-test.pl 
                Rate  mac_processes        ps_grep      osascript do_applescript
mac_processes  248/s             --           -22%           -23%           -27%
ps_grep        317/s            28%             --            -1%            -7%
osascript      321/s            29%             1%             --            -6%
do_applescript 340/s            37%             7%             6%             --

