Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to time an arbitrary function in f#

here's the problem. I need to time a function in f# using another function. I have this piece of code

let time f a =
  let start = System.DateTime.Now in
  let res = (fun f a -> f(a)) in
  let finish = System.DateTime.Now in
  (res, finish - start)

which I'm trying to call saying

time ackermann (2,9);;

I have a function ackermann that takes a tuple (s,n) as argument Probably something fundamentally wrong with this but I don't think I'm far away from a solution that could and looks somewhat like this.

Any suggestions?

Oh btw. the error message I'm getting is saying :

stdin(19,1): error FS0030: Value restriction. The value 'it' has been inferred to have generic type val it : (('_a -> '_b) -> '_a -> '_b) * System.TimeSpan
Either define 'it' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation.

like image 530
PNS Avatar asked Jul 09 '26 00:07

PNS


2 Answers

You have at least two issues:

  1. Try let res = f a. You already have values f and a in scope, but you're currently defining res as a function which takes a new f and applies it to a new a.
  2. Don't use DateTimes (which are appropriate for representing dates and times, but not short durations). Instead, you should be using a System.Diagnostics.Stopwatch.
like image 155
kvb Avatar answered Jul 10 '26 15:07

kvb


You can do something like this:

let time f =
  let sw = System.Diagnostics.Stopwatch.StartNew()
  let r = f()
  sw.Stop()
  printfn "%O" sw.Elapsed
  r

Usage

time (fun () -> System.Threading.Thread.Sleep(100))

I usually keep the following in my code files when sending a bunch of stuff to fsi.

#if INTERACTIVE
#time "on"
#endif

That turns on fsi's built-in timing, which provides more than just execution time:

Real: 00:00:00.099, CPU: 00:00:00.000, GC gen0: 0, gen1: 0, gen2: 0
like image 40
Daniel Avatar answered Jul 10 '26 14:07

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!