Creating an optimized system is not always easy; there are so many places bottlenecks can occur, and understanding how the different parts of the system behaves are not always trivial.
The solution is called execution time profiling, that helps you measure how long time different parts of the system executes. Most Cortex-M devices enables execution time profiling without any expensive debug hardware, thanks to Serial Wire Viewer (SWV) event tracing.
The SWV Statistical Profiling view of the debugger uses the Serial Wire Viewer program counter (PC) sampling, to provide statistical samples of where the CPU executes code at periodic snapshots. This enables the debugger to work out in which C-functions execution is made most often, thus enabling an execution time profiling feature.
As the program counter values are only received at periodic snapshots, the profiling is built on statistical trends, rather than exact and 100% accurate information. It is for example possible that execution of a function (that may be running frequently) is completely missed if the PC samples by random happens to be taken at snapshot times where the processor is executing other code.
Over time however, this risk becomes smaller and smaller, and so the statistical profiling feature still is very valuable in understanding where in your program execution spend most time.
Additionally, it is possible to use the ITM software trace functionality of SWV to set a start and stop trigger in any location of the code, and measure the time between them. That way, you can measure the time between two code lines irrespective of where they are in the code structure; such as across functions or in an arbitrary place in the function.
To learn more on advanced Cortex-M debugging, read our whitepaper!