Script Timer

@Shane Stanley announced his timer here:
[ANN] Script timer

And somewhere else, he provided the ASObjC code that also will time a script.

I was given Shane’s code by Chris Stone, and found it very useful.
I’d like to thank Shane and Chris, and give back a little.

I refactored Shane’s code into a handler:

EDIT: Sun, Feb 21, 2016 at 11:50 PM CST
¢ Going forward, this code will be maintained at:
AppleScript Script Timer using ASObjC
¢ I have just posted an update


###””””””””””””””””””””””””””””””””””””””””””””””
#      timer(pAction)             Calculate and Log Execution Time
#
#      Ver 1.0    2016-02-21
#
#      REF:  The base ASObjC code was provided by Shane Stanley
###””””””””””””””””””””””””””””””””””””””””””””””

on timer(pAction)
	(*
  ### Requires these two statements at top of main script: ###
       use scripting additions
       use framework "Foundation"
*)
	global gTimerStartDate
	if (pAction = "start") then
		set gTimerStartDate to current application's NSDate's |date|()
		log "START: " & ((current date) as text)
	else
		log pAction & ":  
    ¢ " & ((current date) as text) & "
    ¢ EXECUTION TIME: " & (round (-(gTimerStartDate's timeIntervalSinceNow())) * 1000) / 1000.0
	end if
end timer

Here is a demo script:


use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

timer("Start")

# YOUR CODE
--- NOTE:  The below shell scripts have nothing to do with the timer() handler ---

set cmdStr to "perl -e 'use Time::HiRes qw(time); print time'"
set timeStart to do shell script cmdStr
timer("After First Shell Script")
set timeStop to do shell script cmdStr

timer("STOP")

The Log Output looks like this:


(*START: Sun, Feb 21, 2016 at   9:08 PM*)
(*After First Shell Script:  
    ¢ Sun, Feb 21, 2016 at   9:08 PM
    ¢ EXECUTION TIME: 0.035*)
(*STOP:  
    ¢ Sun, Feb 21, 2016 at   9:08 PM
    ¢ EXECUTION TIME: 0.069*)

Since the title of this topic is so general I think this example will fit here as well. If you have AppleScript Toolbox installed you can simply time your script using AppleScript Toolbox. Keep in mind that at midnight the timer resets to 0 which can give weird results.


set startTime to (AST format date "A") as integer
do shell script "sleep 0.5" -- do something that takes time
set stopTime to (AST format date "A") as integer

return stopTime - startTime --return time in milliseconds.