Of course. Measuring the performance difference between executing code from XIP (eXecute-In-Place) memory (like external QSPI flash) versus the microcontroller's internal flash is a critical task for system optimization. Here’s a comprehensive guide on how to do it, from the underlying concepts to practical measurement techniques.
1. Understanding the Fundamental Differences
First, let's understand why there's a performance difference at all.
| Feature | Internal Flash | XIP (External QSPI Flash) |
|---|
| Bus Interface | Wide, parallel bus (e.g., 32, 64, or 128-bit) directly connected to the CPU core via a bus matrix. | Narrow, serial bus (Quad SPI = 4 data lines). |
| Latency | Very low. The CPU often only needs a few clock cycles (plus wait states) to fetch an instruction. | Significantly higher. A full command sequence (command, address, dummy cycles) must be sent over the serial bus before data returns. |
| Bandwidth | Very high. A single read can fetch multiple instructions. | Lower. Limited by the QSPI clock speed and the overhead of the protocol. |
| Performance Trick | Prefetch Buffers / ART Accelerators. These hardware units speculatively fetch the next sequential instructions to hide flash latency. | Cache (Instruction & Data Cache). This is CRITICAL. A small, fast on-chip SRAM cache stores recently used code/data from the external flash. Performance is great on a cache hit and terrible on a cache miss. |
| Power | Generally lower power, as the entire memory interface is on-chip. | Higher power, as it requires driving the external QSPI interface and powering the external flash chip. |
The key takeaway: Performance from internal flash is generally fast and consistent. Performance from XIP is entirely dependent on the cache hit rate.
2. Step-by-Step Measurement Methodology
Here's how you can set up a robust test environment to compare the two.
Prerequisites
- Hardware: Your microcontroller board with both internal flash and a connected QSPI flash chip.
- Tools:
- An IDE/toolchain (e.g., Keil MDK, IAR EWARM, STM32CubeIDE, MCUXpresso).
- A debugger (e.g., ST-LINK, J-Link).
- (Recommended) An oscilloscope or logic analyzer for the most direct timing measurements.
- Knowledge: Basic understanding of your MCU's memory map and how to modify linker scripts.
Step 1: Configure Your Project for Both Scenarios
You need to create two build configurations or two separate projects to place your test code in the desired memory location. This is primarily done using the linker script (.ld or .sct file).
Scenario A: Code in Internal Flash (The Baseline)
This is the default for most projects. The linker script will place the .text (code) and .rodata (constants) sections into the FLASH memory region.
Example Linker Script Snippet (for .ld file):
MEMORY
{
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1024K /* Internal Flash */
QSPI (rx) : ORIGIN = 0x90000000, LENGTH = 8192K /* External QSPI */
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 512K
}
SECTIONS
{
.text :
{
*(.text*) /* Place all code here */
} > FLASH /* <<< Place in Internal Flash */
}
Scenario B: Code in XIP Memory
This requires more setup:
- QSPI Initialization: Your startup code (
startup_xyz.s) or an early SystemInit() function must initialize the QSPI controller and configure the external flash for memory-mapped mode before any code from it is executed.
- Linker Script Modification: You need to tell the linker to place your test functions into the QSPI memory region. It's best practice to create a new section for this.
Example Linker Script Snippet (for .ld file):
MEMORY
{
/* ... same as above ... */
}
SECTIONS
{
/* A special section for code to be placed in QSPI */
.xip_section :
{
. = ALIGN(4);
*(.xip_section*) /* Match functions with this attribute */
. = ALIGN(4);
} > QSPI /* <<< Place in External Flash */
/* Keep the rest of the code in internal flash */
.text :
{
*(.text*)
} > FLASH
}
- Attribute Your Test Functions: In your C code, use compiler attributes to place specific functions into your new section.
// Place this specific function into the .xip_section defined in the linker script
__attribute__((section(".xip_section")))
void my_dsp_routine_in_xip(void) {
// ... algorithm to be tested ...
}
void my_dsp_routine_in_internal_flash(void) {
// ... identical algorithm for comparison ...
}
Step 2: Choose Your Measurement Technique
Here are three effective methods, from simple to highly precise.
Method 1: GPIO Toggling (Simple and Reliable)
This is the most straightforward way to get a real-world execution time.
- Implementation:
// Configure a GPIO pin as a fast output
// ... GPIO_Init() ...
// --- Measure a function in Internal Flash ---
HAL_GPIO_WritePin(TEST_PORT, TEST_PIN, GPIO_PIN_SET); // Pin HIGH
my_dsp_routine_in_internal_flash();
HAL_GPIO_WritePin(TEST_PORT, TEST_PIN, GPIO_PIN_RESET); // Pin LOW
// --- Measure the same function from XIP ---
// Ensure cache is disabled/flushed before the test for a worst-case measurement
#if defined (SCB_InvalidateICache)
SCB_InvalidateICache();
#endif
HAL_GPIO_WritePin(TEST_PORT, TEST_PIN, GPIO_PIN_SET); // Pin HIGH
my_dsp_routine_in_xip();
HAL_GPIO_WritePin(TEST_PORT, TEST_PIN, GPIO_PIN_RESET); // Pin LOW
- Measurement: Use an oscilloscope or logic analyzer to measure the width of the positive pulse. This is your exact execution time.
- Pros: Measures a true wall-clock time, including all latencies and stalls. It's immune to system interrupts if they don't occur during the very short test.
- Cons: Requires external hardware.
Method 2: Using a Hardware Timer
Use one of the MCU's internal high-resolution timers (e.g., a 32-bit TIM on an STM32).
- Implementation:
// Configure a 32-bit timer to count up with a fast clock source (e.g., CPU clock)
// ... TIM_Init() ...
uint32_t start_time, end_time, elapsed_ticks;
__HAL_TIM_SET_COUNTER(&htim, 0); // Reset timer
HAL_TIM_Base_Start(&htim);
my_dsp_routine_in_internal_flash();
HAL_TIM_Base_Stop(&htim);
elapsed_ticks = __HAL_TIM_GET_COUNTER(&htim);
printf("Internal Flash Ticks: %lu\n", elapsed_ticks);
- Pros: No external hardware needed. High precision.
- Cons: The overhead of starting/stopping the timer adds a small error. The timer itself might be slower than the CPU core clock.
Method 3: Using the Core's Cycle Counter (Most Precise)
For ARM Cortex-M3/M4/M7/M33 cores, the DWT (Data Watchpoint and Trace) unit has a cycle counter. This is the most accurate way to measure CPU core cycles.
- Implementation:
// Enable the DWT Cycle Counter
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
uint32_t start_cycles, end_cycles, total_cycles;
// --- Measure Internal Flash ---
DWT->CYCCNT = 0; // Reset cycle counter
start_cycles = DWT->CYCCNT;
my_dsp_routine_in_internal_flash();
end_cycles = DWT->CYCCNT;
total_cycles = end_cycles - start_cycles;
printf("Internal Flash Cycles: %lu\n", total_cycles);
// --- Measure XIP ---
// Flush cache for a fair "first run" test
#if defined (SCB_InvalidateICache)
SCB_InvalidateICache();
#endif
DWT->CYCCNT = 0;
start_cycles = DWT->CYCCNT;
my_dsp_routine_in_xip();
end_cycles = DWT->CYCCNT;
total_cycles = end_cycles - start_cycles;
printf("XIP (first run, cache miss) Cycles: %lu\n", total_cycles);
// --- Measure XIP again to see cache effect ---
DWT->CYCCNT = 0;
start_cycles = DWT->CYCCNT;
my_dsp_routine_in_xip(); // This time, code should be in the cache
end_cycles = DWT->CYCCNT;
total_cycles = end_cycles - start_cycles;
printf("XIP (second run, cache hit) Cycles: %lu\n", total_cycles);
- Pros: Extremely precise (counts actual CPU core cycles). Measures stalls due to memory access.
- Cons: Not available on all cores (e.g., Cortex-M0/M0+). The overhead of reading the register is minimal but exists.
Step 3: What to Test (Critical Test Cases)
Don't just test one function. Test different code patterns to understand the behavior of the cache.
-
Linear Code (Best-case for Prefetch/Cache): A simple for loop performing a mathematical calculation (e.g., multiply-accumulate).
- Expected Result: XIP performance will be very close to internal flash after the first few instructions are cached, as the cache and the flash's prefetch buffer can easily predict the next instruction.
-
Code with Frequent Jumps (Worst-case for Cache): A large switch statement or a function that calls many other small, non-local functions.
- Expected Result: XIP will perform significantly worse. Every jump to an address not in the cache will cause a cache miss, forcing a slow fetch from external flash. This is where you see the biggest performance penalty.
-
Real-World Algorithm: Test a complete, meaningful function from your application, like an FFT, a PID controller loop, or a graphics rendering function.
- Expected Result: This gives you the most realistic performance metric for your specific application.
-
Data Access: Test access to constant data (e.g., lookup tables) placed in both memories.
- Place the code in internal flash and the data (
const uint32_t table[]) in XIP memory, and vice-versa. This helps you decide where to store large assets.
Summary and Analysis of Results
When you get your numbers, you will likely observe:
- Internal Flash: Execution time is highly predictable and consistently fast.
- XIP (First Run / Cache Disabled): Very slow. This is your worst-case scenario.
- XIP (Subsequent Runs / Cache Enabled): Much faster, potentially approaching internal flash speeds if the entire function fits in the cache and is executed linearly.
Your final decision on where to place code should be based on these measurements.
- Performance-critical, frequently called code (e.g., ISRs, DSP routines): Keep in internal flash or tightly-coupled memory (TCM).
- Large, less-frequently executed code (e.g., UI menus, initialization routines, non-critical tasks): A perfect candidate for XIP memory.