ats

How can I measure the time taken to execute a function call in ATS?


Say I wrote a function foo and I would like to find out the time taken to execute foo(1000). Is there already a package available for doing this?


Solution

  • If seconds-resolution is OK, you can #include "libats/libc/DATS/time.dats" and then use time() and difftime():

    implement main0() = {
      val before = time()
      val _ = foo(1000)
      val () = println!(difftime(time(), before))
    }
    

    If you'd like finer resolution you can, under Linux, use libc's gettimeofday():

    extern fun reset_timer(): void = "ext#reset_timer"
    extern fun elapsed_time(): double = "ext#elapsed_time"
    %{
    #include <sys/time.h>
    #include <time.h>
    struct timeval timer_timeval;
    void reset_timer() { gettimeofday(&timer_timeval, NULL); }
    double elapsed_time() {
      struct timeval now;
      gettimeofday(&now, NULL);
      int secs = now.tv_sec - timer_timeval.tv_sec;
      double ms = (now.tv_usec - timer_timeval.tv_usec) / ((double)1000000);
      return(secs + ms);
    }
    %}
    
    /* OCaml-style helper to ignore the value of foo(1000) */
    fn {a:t@ype} ignore(x: a): void = ()
    
    implement main0() =
      begin
        reset_timer();
        ignore(foo(1000));
        println!("foo(1000) took: ", elapsed_time(), "s");
      end
    

    Output (where foo(1000) takes about 3000.3 milliseconds):

    foo(1000) took: 3.000296s