Last active
February 23, 2017 13:23
-
-
Save davidpdrsn/7007115 to your computer and use it in GitHub Desktop.
Functions to time other functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local | |
(* sum of a list of ints | |
sum : int list -> int *) | |
fun sum l = foldl op+ 0 l | |
(* avarage of a list of ints | |
avg : int list -> real *) | |
fun avg l = real(sum(l)) / real(length(l)) | |
in | |
(* calculate the amount of time it takes to run a function once | |
returns the time in milliseconds | |
time : (unit -> a') -> int *) | |
fun time f = | |
let | |
val timer = Timer.startRealTimer() | |
val _ = f() | |
val time = Timer.checkRealTimer timer | |
in Time.toMilliseconds time | |
end | |
(* calculate the avarage amount of time it takes to run a function | |
100 times | |
returns the avarage time in milliseconds | |
avgTime : (unit -> a') -> real *) | |
fun avgTime f = | |
let | |
fun helper (0, acc) = avg acc | |
| helper (n, acc) = helper (n-1, time(f) :: acc) | |
in helper (100, []) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use "./timer.sml"; | |
fun fib 0 = 0 | |
| fib 1 = 1 | |
| fib n = fib(n-1) + fib(n-2) | |
val fibAvg = avgTime (fn () => fib 20) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment