Task

Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.

Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.

This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.




procedure timef(f)                               #: time a function f
local gcol,alloc,used,size,runtime,header,x,i
 
title := ["","total","static","string","block"]  # headings
collect()                                        # start with collected memory (before baseline)
every put(gcol  := [], -&collections)            # baseline collections count
every put(alloc := [], -&allocated)              # . total allocated space by region
every put(used  := [], -&storage)                # . currently used space by region - no total
every put(size  := [], -&regions)                # . current size of regions        - no total
 
write("Performance and Timing measurement for ",image(f),":")  
runtime := &time                                 # base time  
f()
write("Execution time=",&time-runtime," ms.")
 
every (i := 0, x := &collections) do  gcol[i +:= 1] +:= x
every (i := 0, x := &allocated  ) do alloc[i +:= 1] +:= x
every (i := 0, x := &storage    ) do  used[i +:= 1] +:= x
every (i := 0, x := &regions    ) do  size[i +:= 1] +:= x
 
push(gcol,"garbage collections:")
push(alloc,"memory allocated:")
push(used,"N/A","currently used:")
push(size,"N/A","current size:")
 
write("Memory Region and Garbage Collection Summary (delta):")
every (i := 0) <:= *!(title|gcol|alloc|used|size)   
every x := (title|gcol|alloc|used|size) do {
   f := left
   every writes(f(!x,i + 3)) do f := right
   write()
   }
write("Note: static region values should be zero and may not be meaningful.")
return
end