Timing an Ada function

How does one time a function in Ada?

Below is a simple program which tests the run time of a recursive Fibonacci function. It uses the ada package Ada.Calendar, which is able to return time stamps. The variables startTime, and endTime are capable of holding a Time value. A call to Clock(), reads the machine internal clock, and stores the current time of day in the time variable. The difference is stored in a variable of type Duration, expressed in seconds.

Note also the put_line statements which make use of the Image criteria – X’Image(Y) is an Ada attribute where X is any discrete type and Y is an instance of that type. This attribute returns a string representation of the value passed as input.

And if you want to time another language check out the Wikipedia site on system timing.

with Ada.Text_IO; use Ada.Text_IO;
with ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Calendar; use Ada.Calendar;
with Ada.Text_Io; use Ada.Text_Io;

procedure testFibonacci is

    function fibonacci(n : in integer) return integer is
    begin 
        if n = 0 then
            return 0;
        elsif n = 1 then
            return 1;
        else
            return fibonacci(n-1) + fibonacci(n-2);
        end if;
    end fibonacci;

    n : integer;
    startTime, endTime : Time;
    milliS : Duration;
    result : integer;

begin
    put_line("Fibonacci number: ");
    get(n);
    startTime := Clock;
    result := fibonacci(n);
    endTime := Clock;
    milliS := (endTime - startTime) * 1000;

    put_line("Result: " & Integer'Image(result));
    put_line("Runtime = " & Duration'Image(milliS) & " milliseconds.");
 
end testFibonacci;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s