Page 191 - ARM Based Microcontroller Projects Using MBED
P. 191
8.13 PROJECT 10—LOOP EXECUTION TIMES 177
8.13.4 Program Listing
Fig. 8.38 shows the program listing (program: Loops). At the beginning of the program, a
heading is displayed. Then, two for loops are formed. The outer loop counts 10 times. The
inner loop is simply a for loop with nothing in its body. The Timer is started just before en-
tering the loop and it is stopped after exiting from the loop. This inner loop iterates j times
where j is initially set to 10,000 and is multiplied every time we enter the inner loop. The time
spent in the loop is extracted using function read_ms which returns the elapsed time in mil-
liseconds. The loop count (j) and the time spent inside the loop are displayed at every iteration
/*************************************************************************
LOOP TIMING
===========
This program measures the loop timing of for loops. The iteration
count is changed from 1000 to 512,000 in multiples of 2 and the
time taken to execute the loop is calculated and displayed on the
PC screen in milliseconds.
Author: Dogan Ibrahim
Date : August 2018
File : Loops
**************************************************************************/
#include "mbed.h"
Serial MyPC(USBTX, USBRX);
Timer tim;
int main()
{
unsigned int j;
float Duration;
j = 10000; // Starting value
MyPC.printf("\n\rIteration no Time(ms)"); // Heading
MyPC.printf("\n\r============================");
for(int n = 1; n <= 10; n++) // For loop
{
tim.reset(); // Reset Timer
tim.start(); // Start Timer
for(int k = 0; k < j; k++) // Loop
{
}
tim.stop(); // Stop Timer
Duration = tim.read_ms(); // Duration (ms)
MyPC.printf("\n\r%d %f", j, Duration); // Display
j = 2 * j; // New j
}
printf("\n\r"); // New line
}
FIG. 8.38 Program listing.