Measuring Time
A real-time system is correct only if it gets the right answer at the right time. Before we can schedule tasks, close control loops or compare an RTOS with a hand-written loop, we need to put a number on time: how long code takes, how late an interrupt starts, and how much that lateness wobbles. This experiment builds those measuring tools. Every later experiment uses them.
You already know the TM4C123's GPIO, timers and interrupts from ENCS4110. Here they become instruments.
Objectives
- Measure how long a piece of code takes, with a debug pin on a logic analyzer and with the cycle counter, and compare the two.
- Measure the latency of a periodic timer interrupt and its jitter.
- Show how a second interrupt disturbs the first, and fix it with NVIC priorities.
- Build a profiler that records the worst-case execution time of any function.
Background
Time words
| Term | Meaning | Example in this experiment |
|---|---|---|
| Execution time | How long a piece of code takes to run once | busy_work(200) |
| Worst-case execution time (WCET) | The longest execution time ever seen, or proven | work_max, p.max |
| Period | How often a periodic task should start | Timer1A: every 1 ms |
| Deadline | When the task must be finished | Before the next period |
| Latency | How late the task starts, measured from the event that should start it | Timer time-out to the first line of the handler |
| Jitter | How much the latency (or the period) varies from one run to the next | lat_max - lat_min |
A system with a hard deadline fails if it is ever late, like an airbag or a motor current limit. A soft deadline only degrades when missed, like a video frame. Either way, the worst case matters more than the average.
Three ways to measure time
| Method | Resolution | Range before it wraps | Cost to the program |
|---|---|---|---|
| Debug pin + logic analyzer | About 42 ns at 24 MHz sampling | As long as the capture | Two store instructions |
| SysTick (24-bit, counts down) | 1 cycle (20 ns) | 224 cycles, about 335 ms | Two loads; used by the RTOS later |
| DWT cycle counter (32-bit, counts up) | 1 cycle (20 ns) | 232 cycles, about 86 s | Two loads |
The debug pin shows when things happen and how they overlap, on several channels at once. The cycle counter gives exact numbers the program itself can keep, such as the worst case so far. We use both, and check that they agree.
Debug pins with bit-specific addressing
A debug pin must change fast and without disturbing other pins, even from inside an interrupt. A normal GPIOE->DATA |= D0 is a read-modify-write: three instructions, and an interrupt landing in the middle can lose another pin's change.
The TM4C123 avoids this with bit-specific addressing: the DATA register appears at 256 addresses, and address bits 9 to 2 choose which pins a write may change. To change only PE1 (bit 1, mask 0x02), write to GPIOE_BASE + (0x02 << 2) = GPIOE_BASE + 0x008:
#define PORTE_BITS(p) (*((volatile uint32_t *)(GPIOE_BASE + ((p) << 2))))
#define PIN_HIGH(p) (PORTE_BITS(p) = (p)) // only the pins in p go high
#define PIN_LOW(p) (PORTE_BITS(p) = 0) // only the pins in p go lowOne store instruction, and every other pin on Port E is untouched. The datasheet calls this Data Register Operation in the GPIO chapter.
The cycle counter (DWT CYCCNT)
The Cortex-M4 core has a Data Watchpoint and Trace (DWT) unit for debuggers. One of its registers, CYCCNT, counts every clock cycle. It is off after reset; two writes turn it on:
| Register | Bit | Meaning |
|---|---|---|
CoreDebug->DEMCR | TRCENA (bit 24) | Turn on the trace and debug blocks, DWT included |
DWT->CTRL | CYCCNTENA (bit 0) | Start CYCCNT counting |
DWT->CYCCNT | all 32 | The count: read it, or write 0 to restart |
To time code, read CYCCNT before and after and subtract. Unsigned subtraction gives the right answer even if the counter wrapped in between, as long as less than 232 cycles passed. At 50 MHz, 50 cycles are 1 µs.
Measuring interrupt latency with the timer itself
When Timer1A reaches zero it raises its time-out flag, reloads TAILR and keeps counting down. So inside the handler,
uint32_t latency = TIMER1->TAILR - TIMER1->TAV;is the number of cycles since the time-out: the interrupt latency, plus the few cycles the handler took to reach this line. No extra hardware is needed, and the program can keep the shortest and longest latency it has seen.
Arm specifies a 12-cycle latency from an interrupt request to the first instruction of its handler on the Cortex-M4. Your measurement will be higher: it includes the handler's own first instructions, flash wait states, and, most importantly, whatever the CPU was busy with when the time-out came.
Why latency varies: priorities
The NVIC decides what runs when two interrupts want the CPU. Each interrupt has a priority from 0 (highest) to 7 (lowest) on the TM4C123.
- Same priority: a new interrupt waits until the running handler finishes. Its latency grows by up to the whole length of the other handler.
- Higher priority (lower number): it preempts the running handler, which resumes afterwards. Its latency stays small.
So the jitter of a periodic task depends on every interrupt at the same or higher priority. Lengthening any one handler can make another task late.
Activity
One program that times a function two ways, measures the latency and jitter of a 1 kHz timer interrupt, and, with two switches, shows a second interrupt making it late and a priority change fixing it.
Setting up
Create a LaunchPad project in Keil as in ENCS4110's Tiva LaunchPad Project guide, and install PulseView from the Logic Analyzer guide.
Step 1: Wire the analyzer and add the definitions
| Logic analyzer | LaunchPad | Shows |
|---|---|---|
| GND | GND | Connect this first |
| CH0 | PE1 (D0) | busy_work() running in main |
| CH1 | PE2 (D1) | The Timer1A handler running |
| CH2 | PE3 (D2) | The Timer2A handler running (once you turn it on) |
#include "TM4C123.h"
// Clocks
#define RCGC_GPIOE (1U << 4) // RCGCGPIO bit for Port E
#define RCGC_TIMER1 (1U << 1) // RCGCTIMER bit for Timer1
#define RCGC_TIMER2 (1U << 2) // RCGCTIMER bit for Timer2
// Debug pins on Port E, one per thing we time. Wire each to a logic analyzer channel.
#define D0 (1U << 1) // PE1: high while busy_work() runs
#define D1 (1U << 2) // PE2: high while the Timer1A handler runs
#define D2 (1U << 3) // PE3: high while the Timer2A handler runs
#define DEBUG_PINS (D0 | D1 | D2)
// Bit-specific addressing: writing to GPIOE_BASE + (pins << 2) changes only those pins,
// in one store instruction. No read-modify-write, so it is fast and safe inside interrupts.
#define PORTE_BITS(p) (*((volatile uint32_t *)(GPIOE_BASE + ((p) << 2))))
#define PIN_HIGH(p) (PORTE_BITS(p) = (p))
#define PIN_LOW(p) (PORTE_BITS(p) = 0)
// Timer register values (same as ENCS4110)
#define CFG_32BIT 0x0 // CFG: one 32-bit timer
#define TAMR_PERIODIC 0x2 // TAMR: periodic, counting down
#define CTL_TAEN (1U << 0) // CTL: Timer A enable
#define TATO (1U << 0) // IMR, ICR: Timer A time-out
// Timing
#define TICK_HZ 1000 // Timer1A: the periodic task, 1 kHz
#define TICK_LOAD (SystemCoreClock / TICK_HZ - 1) // 49,999 at 50 MHz
#define DISTURB_HZ 1700 // Timer2A: a second interrupt, not a multiple of 1 kHz
#define DISTURB_LOAD (SystemCoreClock / DISTURB_HZ - 1)
#define WORK_N 200 // Loop count for the function main() times
#define DISTURB_WORK 250 // Loop count inside the Timer2A handler
// Experiment switches: change these and rebuild (see "More to try")
#define DISTURB 0 // 1: start Timer2A, a second, slow interrupt
#define TIMER1_PRIO 2 // NVIC priority, 0 (highest) to 7 (lowest)
#define TIMER2_PRIO 2
// Results, read in the Watch window. All in clock cycles (50 per microsecond).
volatile uint32_t work_cycles; // The last busy_work() time
volatile uint32_t work_min = 0xFFFFFFFF; // Shortest busy_work() time seen
volatile uint32_t work_max; // Longest busy_work() time seen
volatile uint32_t lat_min = 0xFFFFFFFF; // Shortest Timer1A interrupt latency
volatile uint32_t lat_max; // Longest Timer1A interrupt latency
volatile uint32_t ticks; // Timer1A interrupts so farD0,D1,D2are free Port E pins, one per thing we time.PIN_HIGHandPIN_LOWuse bit-specific addressing: one store each, safe in interrupts.TICK_LOADmakes Timer1A time out every 1 ms.DISTURB_HZis 1700 Hz on purpose: not a multiple of 1 kHz, so the two interrupts collide at a different moment every time.DISTURB,TIMER1_PRIOandTIMER2_PRIOare switches for More to try. Leave them as they are for now.- The
volatileresults are what you read in the Watch window. All are in clock cycles.
Step 2: Add the helpers and the interrupt handlers
// The cycle counter (DWT CYCCNT): a 32-bit counter in the Cortex-M4 core that
// counts every clock cycle. It wraps after 2^32 cycles, about 86 s at 50 MHz.
void cycles_init(void)
{
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; // Turn on the core's trace block
DWT->CYCCNT = 0;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; // Start counting
}
void debug_pins_init(void)
{
SYSCTL->RCGCGPIO |= RCGC_GPIOE;
while ((SYSCTL->PRGPIO & RCGC_GPIOE) == 0) {} // Wait until Port E is ready
GPIOE->DIR |= DEBUG_PINS;
GPIOE->DEN |= DEBUG_PINS;
PIN_LOW(DEBUG_PINS);
}
// Something to time: an empty loop. volatile stops the compiler from removing it.
void busy_work(uint32_t n)
{
for (volatile uint32_t i = 0; i < n; i++) {}
}
// A periodic interrupt from a 32-bit timer, as in ENCS4110 Experiment 7.
void timer_periodic(TIMER0_Type *timer, uint32_t load)
{
timer->CTL = 0; // Stop it while we set it up
timer->CFG = CFG_32BIT;
timer->TAMR = TAMR_PERIODIC;
timer->TAILR = load;
timer->ICR = TATO;
timer->IMR = TATO;
timer->CTL = CTL_TAEN;
}cycles_init()turns on the DWT cycle counter: trace on (TRCENA), counter on (CYCCNTENA).debug_pins_init()waits onPRGPIOuntil Port E is ready before touching it, then makes the three pins digital outputs.busy_work(n)is the code we time. Thevolatileloop counter stops the compiler from deleting a loop that has no visible effect.timer_periodic()is the ENCS4110 periodic-timer setup, written once for any timer.
// The periodic task. Its first job is to work out how late it started.
void TIMER1A_Handler(void)
{
// The timer counts down from TAILR and reloads at the time-out, so
// TAILR - TAV is the number of cycles since the time-out: the latency.
uint32_t latency = TIMER1->TAILR - TIMER1->TAV;
PIN_HIGH(D1);
TIMER1->ICR = TATO; // Acknowledge the interrupt
if (latency < lat_min) lat_min = latency;
if (latency > lat_max) lat_max = latency;
ticks++;
PIN_LOW(D1);
}
// A second interrupt that does some slow work, to disturb the first.
void TIMER2A_Handler(void)
{
PIN_HIGH(D2);
TIMER2->ICR = TATO;
busy_work(DISTURB_WORK);
PIN_LOW(D2);
}TIMER1A_Handlerreads the latency first, before anything else can add to it, then raises D1 so the analyzer sees the handler run.lat_minandlat_maxkeep the best and worst case. Their difference is the jitter.TIMER2A_Handlerdoes nothing useful: it just takes time, like a slow driver for a peripheral would.
Step 3: Write main
int main(void)
{
cycles_init();
debug_pins_init();
// Timer1A: the 1 kHz periodic task
SYSCTL->RCGCTIMER |= RCGC_TIMER1;
while ((SYSCTL->PRTIMER & RCGC_TIMER1) == 0) {}
timer_periodic(TIMER1, TICK_LOAD);
NVIC_SetPriority(TIMER1A_IRQn, TIMER1_PRIO);
NVIC_EnableIRQ(TIMER1A_IRQn);
// Timer2A: the disturbing interrupt, only when DISTURB is 1
if (DISTURB)
{
SYSCTL->RCGCTIMER |= RCGC_TIMER2;
while ((SYSCTL->PRTIMER & RCGC_TIMER2) == 0) {}
timer_periodic(TIMER2, DISTURB_LOAD);
NVIC_SetPriority(TIMER2A_IRQn, TIMER2_PRIO);
NVIC_EnableIRQ(TIMER2A_IRQn);
}
while (1)
{
// Time busy_work() two ways at once: the D0 pin for the logic
// analyzer, and the cycle counter for the Watch window.
uint32_t start = DWT->CYCCNT;
PIN_HIGH(D0);
busy_work(WORK_N);
PIN_LOW(D0);
work_cycles = DWT->CYCCNT - start; // Unsigned subtraction survives a wrap
if (work_cycles < work_min) work_min = work_cycles;
if (work_cycles > work_max) work_max = work_cycles;
busy_work(WORK_N); // A gap, so the D0 pulses are easy to tell apart
}
}startis read before D0 goes high andwork_cyclesafter it goes low, so the count includes the two pin stores. Expect it to be a few cycles longer than the D0 pulse.work_minandwork_maxrecord the range. If the Timer1A interrupt lands insidebusy_work(), that run takes longer: the handler's time is added.- The second
busy_work()is only a gap, so each D0 pulse stands apart on the analyzer.
Build, flash, and run. Open the Watch window (View → Watch Windows → Watch 1) and add work_cycles, work_min, work_max, lat_min, lat_max and ticks. In PulseView, capture for about 50 ms.
Check: ticks climbs by about 1000 a second. D0 pulses repeat on CH0, and a short D1 pulse appears every 1 ms on CH1. work_min divided by 50 is within a fraction of a microsecond of the D0 pulse width.
Then try: compare work_max - work_min with the width of a D1 pulse. The difference is the time the Timer1A interrupt took from busy_work() when it landed inside it.
| Measurement | Cycles | µs |
|---|---|---|
| D0 pulse width (PulseView) | ||
work_min | ||
work_max | ||
lat_min | ||
lat_max | ||
Jitter: lat_max - lat_min |
- Does
ticksgo up by about 1000 a second? - Do the D0 pulse width and
work_minagree, after converting cycles to µs? - Can you explain why
work_maxis larger thanwork_min? - Did you record
lat_min,lat_maxand the jitter?
More to try (optional)
Change one switch at a time, rebuild, and restart (Reset, then Run) so the minimums and maximums start over.
| Try this | What you'll see |
|---|---|
Set DISTURB to 1 | D2 pulses appear on CH2. lat_max jumps to about the D2 pulse width: when Timer1A times out during the Timer2A handler, it has to wait for it to finish. |
Then set TIMER1_PRIO to 1 | Timer1A now has the higher priority and preempts Timer2A. lat_max drops back near lat_min; on the analyzer, D2 pulses sometimes have a D1 pulse inside them. |
Set DISTURB_WORK to 2000 | The Timer2A handler takes longer than 1 ms. With equal priorities, Timer1A interrupts are now delayed by more than a period: ticks falls behind. |
Double WORK_N | work_min roughly doubles. Is it exactly double? The loop has a fixed cost too. |
The complete program
#include "TM4C123.h"
// Clocks
#define RCGC_GPIOE (1U << 4) // RCGCGPIO bit for Port E
#define RCGC_TIMER1 (1U << 1) // RCGCTIMER bit for Timer1
#define RCGC_TIMER2 (1U << 2) // RCGCTIMER bit for Timer2
// Debug pins on Port E, one per thing we time. Wire each to a logic analyzer channel.
#define D0 (1U << 1) // PE1: high while busy_work() runs
#define D1 (1U << 2) // PE2: high while the Timer1A handler runs
#define D2 (1U << 3) // PE3: high while the Timer2A handler runs
#define DEBUG_PINS (D0 | D1 | D2)
// Bit-specific addressing: writing to GPIOE_BASE + (pins << 2) changes only those pins,
// in one store instruction. No read-modify-write, so it is fast and safe inside interrupts.
#define PORTE_BITS(p) (*((volatile uint32_t *)(GPIOE_BASE + ((p) << 2))))
#define PIN_HIGH(p) (PORTE_BITS(p) = (p))
#define PIN_LOW(p) (PORTE_BITS(p) = 0)
// Timer register values (same as ENCS4110)
#define CFG_32BIT 0x0 // CFG: one 32-bit timer
#define TAMR_PERIODIC 0x2 // TAMR: periodic, counting down
#define CTL_TAEN (1U << 0) // CTL: Timer A enable
#define TATO (1U << 0) // IMR, ICR: Timer A time-out
// Timing
#define TICK_HZ 1000 // Timer1A: the periodic task, 1 kHz
#define TICK_LOAD (SystemCoreClock / TICK_HZ - 1) // 49,999 at 50 MHz
#define DISTURB_HZ 1700 // Timer2A: a second interrupt, not a multiple of 1 kHz
#define DISTURB_LOAD (SystemCoreClock / DISTURB_HZ - 1)
#define WORK_N 200 // Loop count for the function main() times
#define DISTURB_WORK 250 // Loop count inside the Timer2A handler
// Experiment switches: change these and rebuild (see "More to try")
#define DISTURB 0 // 1: start Timer2A, a second, slow interrupt
#define TIMER1_PRIO 2 // NVIC priority, 0 (highest) to 7 (lowest)
#define TIMER2_PRIO 2
// Results, read in the Watch window. All in clock cycles (50 per microsecond).
volatile uint32_t work_cycles; // The last busy_work() time
volatile uint32_t work_min = 0xFFFFFFFF; // Shortest busy_work() time seen
volatile uint32_t work_max; // Longest busy_work() time seen
volatile uint32_t lat_min = 0xFFFFFFFF; // Shortest Timer1A interrupt latency
volatile uint32_t lat_max; // Longest Timer1A interrupt latency
volatile uint32_t ticks; // Timer1A interrupts so far
// The cycle counter (DWT CYCCNT): a 32-bit counter in the Cortex-M4 core that
// counts every clock cycle. It wraps after 2^32 cycles, about 86 s at 50 MHz.
void cycles_init(void)
{
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; // Turn on the core's trace block
DWT->CYCCNT = 0;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; // Start counting
}
void debug_pins_init(void)
{
SYSCTL->RCGCGPIO |= RCGC_GPIOE;
while ((SYSCTL->PRGPIO & RCGC_GPIOE) == 0) {} // Wait until Port E is ready
GPIOE->DIR |= DEBUG_PINS;
GPIOE->DEN |= DEBUG_PINS;
PIN_LOW(DEBUG_PINS);
}
// Something to time: an empty loop. volatile stops the compiler from removing it.
void busy_work(uint32_t n)
{
for (volatile uint32_t i = 0; i < n; i++) {}
}
// A periodic interrupt from a 32-bit timer, as in ENCS4110 Experiment 7.
void timer_periodic(TIMER0_Type *timer, uint32_t load)
{
timer->CTL = 0; // Stop it while we set it up
timer->CFG = CFG_32BIT;
timer->TAMR = TAMR_PERIODIC;
timer->TAILR = load;
timer->ICR = TATO;
timer->IMR = TATO;
timer->CTL = CTL_TAEN;
}
// The periodic task. Its first job is to work out how late it started.
void TIMER1A_Handler(void)
{
// The timer counts down from TAILR and reloads at the time-out, so
// TAILR - TAV is the number of cycles since the time-out: the latency.
uint32_t latency = TIMER1->TAILR - TIMER1->TAV;
PIN_HIGH(D1);
TIMER1->ICR = TATO; // Acknowledge the interrupt
if (latency < lat_min) lat_min = latency;
if (latency > lat_max) lat_max = latency;
ticks++;
PIN_LOW(D1);
}
// A second interrupt that does some slow work, to disturb the first.
void TIMER2A_Handler(void)
{
PIN_HIGH(D2);
TIMER2->ICR = TATO;
busy_work(DISTURB_WORK);
PIN_LOW(D2);
}
int main(void)
{
cycles_init();
debug_pins_init();
// Timer1A: the 1 kHz periodic task
SYSCTL->RCGCTIMER |= RCGC_TIMER1;
while ((SYSCTL->PRTIMER & RCGC_TIMER1) == 0) {}
timer_periodic(TIMER1, TICK_LOAD);
NVIC_SetPriority(TIMER1A_IRQn, TIMER1_PRIO);
NVIC_EnableIRQ(TIMER1A_IRQn);
// Timer2A: the disturbing interrupt, only when DISTURB is 1
if (DISTURB)
{
SYSCTL->RCGCTIMER |= RCGC_TIMER2;
while ((SYSCTL->PRTIMER & RCGC_TIMER2) == 0) {}
timer_periodic(TIMER2, DISTURB_LOAD);
NVIC_SetPriority(TIMER2A_IRQn, TIMER2_PRIO);
NVIC_EnableIRQ(TIMER2A_IRQn);
}
while (1)
{
// Time busy_work() two ways at once: the D0 pin for the logic
// analyzer, and the cycle counter for the Watch window.
uint32_t start = DWT->CYCCNT;
PIN_HIGH(D0);
busy_work(WORK_N);
PIN_LOW(D0);
work_cycles = DWT->CYCCNT - start; // Unsigned subtraction survives a wrap
if (work_cycles < work_min) work_min = work_cycles;
if (work_cycles > work_max) work_max = work_cycles;
busy_work(WORK_N); // A gap, so the D0 pulses are easy to tell apart
}
}Common problems
| Symptom | Cause and fix |
|---|---|
| All the Watch values stay 0 | The program isn't running, or the Watch window isn't refreshing: enable View → Periodic Window Update in Keil. |
work_cycles is 0 | cycles_init() isn't called, or is called after the first measurement. |
ticks stays 0 | The handler name doesn't match the startup file (it must be exactly TIMER1A_Handler), or NVIC_EnableIRQ is missing. |
| PulseView shows noise or nothing | The analyzer's GND isn't connected to the LaunchPad's GND, or the sample rate is too low for the pulses: use 4 MHz or more. |
lat_min is huge (near 50,000) | The latency is read after TIMER1->ICR or after other code. It must be the first line of the handler. |
Task
Build a profiler: a pair of functions, prof_start() and prof_stop(), that time any piece of code and keep its last, shortest and longest time and a count. Then use it to answer a design question: which of three ways to average 16 ADC samples is fastest, and how long is its worst case?
You will reuse this profiler in every later experiment, so make it right.
The starter program
Start from this program. It compiles and runs, but every profile stays empty: the four TODOs are yours.
// Experiment 1 Task: a reusable profiler.
// Write the four TODOs (highlighted). The rest is provided: don't change it.
#include "TM4C123.h"
#define RCGC_TIMER1 (1U << 1)
#define CFG_32BIT 0x0
#define TAMR_PERIODIC 0x2
#define CTL_TAEN (1U << 0)
#define TATO (1U << 0)
#define TICK_LOAD (SystemCoreClock / 1000 - 1) // Timer1A at 1 kHz, as in the Activity
#define N 16 // Samples per average
#define CYCLES_PER_US (SystemCoreClock / 1000000) // 50 at 50 MHz
// One profile per piece of code you measure. All times are in clock cycles.
typedef struct {
uint32_t start; // CYCCNT when prof_start() ran
uint32_t last; // The latest measurement
uint32_t min; // The shortest seen
uint32_t max; // The longest seen: the worst case
uint32_t count; // How many measurements so far
} profile_t;
// The three functions you will compare, and the timer interrupt.
volatile profile_t p_int = { .min = 0xFFFFFFFF };
volatile profile_t p_shift = { .min = 0xFFFFFFFF };
volatile profile_t p_float = { .min = 0xFFFFFFFF };
volatile profile_t p_isr = { .min = 0xFFFFFFFF };
volatile uint32_t result; // Keeps the averages from being optimised away
uint16_t samples[N]; // Pretend ADC readings, 0 to 4095
void cycles_init(void)
{
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CYCCNT = 0;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
}
// Start timing: remember the cycle counter.
void prof_start(volatile profile_t *p)
{
// TODO 1: save the current cycle count in p->start
}
// Stop timing: work out how long it took and update the record.
void prof_stop(volatile profile_t *p)
{
// TODO 2: the elapsed cycles since prof_start(), stored in p->last
// TODO 3: update p->min, p->max and p->count from p->last
}
// Three ways to average N samples
uint32_t avg_divide(const uint16_t *x) // Sum, then divide
{
uint32_t sum = 0;
for (int i = 0; i < N; i++) sum += x[i];
return sum / N;
}
uint32_t avg_shift(const uint16_t *x) // Sum, then shift: N is 16, so >> 4 divides by 16
{
uint32_t sum = 0;
for (int i = 0; i < N; i++) sum += x[i];
return sum >> 4;
}
uint32_t avg_float(const uint16_t *x) // In floating point, on the Cortex-M4F's FPU
{
float sum = 0.0f;
for (int i = 0; i < N; i++) sum += (float)x[i];
return (uint32_t)(sum / (float)N);
}
// The 1 kHz periodic interrupt from the Activity, now timing itself
void TIMER1A_Handler(void)
{
prof_start(&p_isr);
TIMER1->ICR = TATO;
result = avg_shift(samples);
prof_stop(&p_isr);
}
int main(void)
{
cycles_init();
for (int i = 0; i < N; i++) samples[i] = (uint16_t)(i * 251 % 4096);
SYSCTL->RCGCTIMER |= RCGC_TIMER1;
while ((SYSCTL->PRTIMER & RCGC_TIMER1) == 0) {}
TIMER1->CTL = 0;
TIMER1->CFG = CFG_32BIT;
TIMER1->TAMR = TAMR_PERIODIC;
TIMER1->TAILR = TICK_LOAD;
TIMER1->ICR = TATO;
TIMER1->IMR = TATO;
TIMER1->CTL = CTL_TAEN;
NVIC_EnableIRQ(TIMER1A_IRQn);
while (1)
{
// TODO 4: time each of the three averages with its own profile:
// prof_start(&p_...), result = avg_...(samples), prof_stop(&p_...)
result = avg_divide(samples);
result = avg_shift(samples);
result = avg_float(samples);
}
}How the provided part works
profile_tholds one measurement record. Each function you time gets its own, so the results never mix.avg_divide,avg_shiftandavg_floatcompute the same average three ways: a division, a shift (only possible because 16 is a power of 2), and floating point on the FPU.- The Timer1A handler from the Activity still runs at 1 kHz and times itself with
p_isr, once your TODOs work. It is there to interrupt the main loop, just like a real system would. samples[]holds made-up readings so the averages have something to work on.
What to write: the four TODOs
Each TODO is highlighted in the starter, exactly where its code goes. Write them in order: 1, 2, 3, 4.
TODO 1: start timing (prof_start)
- Save the cycle counter,
DWT->CYCCNT, inp->start. One line.
TODO 2: elapsed time (prof_stop)
- Read
DWT->CYCCNTagain and subtractp->start, as in the Activity'smain. Store it inp->last.
TODO 3: the record (prof_stop)
- If
p->lastis smaller thanp->min, it is the new minimum. Same for the maximum. - Add one to
p->count.
TODO 4: use it (the main loop)
- Wrap each average in its own pair:
prof_start(&p_int)beforeavg_divide,prof_stop(&p_int)after, thenp_shiftforavg_shiftandp_floatforavg_float.
Build, flash, and run. Watch p_int, p_shift, p_float and p_isr in the Watch window (expand each to see its fields).
| Code | min (cycles) | max (cycles) | min (µs) |
|---|---|---|---|
avg_divide | |||
avg_shift | |||
avg_float | |||
Timer1A handler (p_isr) |
- Do all four profiles fill in, with
countclimbing? - Which average is fastest, and by how much? Does the order surprise you?
- Why is
maxmuch larger thanminfor the three averages, but not forp_isr? - What would the worst-case time of
avg_floatbe if a second 1 kHz interrupt of the same length were added?