timing applescripts

when developing a script, it’s sometimes helpful to find out how long the script takes to do its thing. you can then compare different portions or versions of scripts to get the most efficient outcome. rather than sitting there with your stopwatch, you can just build a simple timer into your script.

the current date command gives you … you guessed it … the current date. the beauty of it is that it gives you the current date right down to the second and returns something like this :

date "Wednesday, 5 October 2011 8:02:08 PM"

if you get the current date at the beginning of your script, and then again at the completion, you can compare the two to get the runtime of the script :

set mgStart to current date
---------------------------------------
-- insert applescript code here --
delay 3
---------------------------------------
set mgStop to current date

display dialog "This took " & (mgStop - mgStart) & " seconds."

this will give you a dialog box something like this :

screen grab of 3 seconds dialog box

to time a script in less than seconds (milliseconds), you’d have to track down a separate scripting addition. (see update below)

for those interested in this sort of thing…
you can extract various elements from the current date — to do with as you will. here are a few, no doubt there are other coercions as well :

current date -- "Wednesday, 5 October 2011 8:02:08 PM"

date string of (current date) -- "Wednesday, 5 October 2011"
time string of (current date) -- "8:02:08 PM"

weekday of (current date) -- Wednesday
day of (current date) -- 5
month of (current date) -- October
year of (current date) -- 2011

hours of (current date) -- 20 (note: 24 hour time)
minutes of (current date) -- 2
seconds of (current date) -- 8

time of (current date) -- 72128 (seconds since midnight)
time of (current date)/60 -- 1202.1333333 (minutes since midnight)
weekday of (current date) as number -- 4
month of (current date) as number -- 10

update : 01 November : here’s a timing solution which uses the shell to measure in fractions of seconds — thanks to Alex Zavatone on the applescript-users mailing list :

set mgRightNow to "perl -e 'use Time::HiRes qw(time); print time'"
set mgStart to do shell script mgRightNow
---------------------------------------
-- insert applescript code here --
---------------------------------------
set mgStop to do shell script mgRightNow
set mgRunTime to mgStop - mgStart
display dialog "This took " & mgRunTime & " seconds." & return & "that's " & (round (mgRunTime * 1000)) & " milliseconds."

macgrunt icon