Rate counter: Difference between revisions

Ada implementation
(Go solution)
(Ada implementation)
Line 11:
 
'''See also:''' [[System time]], [[Time a function]]
 
 
=={{header|Ada}}==
Launch 6 jobs in parallel and record the elapsed time for each job.<br>
A variant to get CPU times would use the package Ada.Execution_Time (Ada05).The precision
of measure is given by the value of System.Tick; on Windows value is 10 ms.
<lang Ada>
with System; use System;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Calendar; use Ada.Calendar; use Ada;
with Ada.Synchronous_Task_Control; use Ada.Synchronous_Task_Control;
 
procedure Rate_Counter is
pragma Priority (Max_Priority);
 
package Duration_IO is new Fixed_IO (Duration);
 
Job_Nbr : constant := 6; -- adjust to your need
subtype Job_Index is Natural range 1 .. Job_Nbr;
 
task type Job (ID : Job_Index) is
pragma Priority (Default_Priority);
entry Start;
end Job;
 
type Job_Ptr is access Job;
 
Jobs : array (Job_Index) of Job_Ptr;
 
Flags :
array (Job_Index) of Synchronous_Task_Control.Suspension_Object;
Completed : array (Job_Index) of Boolean := (others => False);
Start_T, Stop_T : array (Job_Index) of Calendar.Time;
 
Done : Natural := 0;
 
task body Job is
Anchor : Long_Integer;
pragma Volatile (Anchor); -- necessary to avoid compiler optimization.
begin
accept Start do
Set_False (Flags (ID));
end Start;
-- the job to do / could be replaced by
for I in Long_Integer'First .. Long_Integer'Last loop
Anchor := I;
end loop;
Set_True (Flags (ID));
end Job;
 
begin
for J in Job_Index'Range loop
Jobs (J) := new Job (ID => J); -- create the jobs first, sync later
end loop;
for J in Job_Index'Range loop -- launch the jobs in parallel
Start_T (J) := Calendar.Clock; -- get the start time
Jobs (J).Start; -- priority settings necessary to regain control.
end loop;
-- Polling for the results
while not (Done = Job_Nbr) loop
for J in Job_Index'Range loop
if not Completed (J) and then Current_State (Flags (J)) then
Stop_T (J) := Calendar.Clock; -- get the end time
Put ("Job #" & Job_Index'Image (J) & " is finished. It took ");
Duration_IO.Put (Stop_T (J) - Start_T (J), Fore => 3, Aft => 2);
Put_Line (" seconds.");
Done := Done + 1;
Completed (J) := True;
end if;
end loop;
delay System.Tick; -- according to the precision of the system clock
end loop;
 
end Rate_Counter;</lang>
 
Output :<pre style="overflow: auto; height: 5em;">
Job # 1 is finished. It took 44.49 seconds.
Job # 3 is finished. It took 44.43 seconds.
Job # 5 is finished. It took 44.32 seconds.
Job # 4 is finished. It took 44.85 seconds.
Job # 2 is finished. It took 45.17 seconds.
Job # 6 is finished. It took 44.99 seconds.</pre>
 
=={{header|C}}==
Anonymous user