3-phase PV router
Loading...
Searching...
No Matches
bench_timer.h
Go to the documentation of this file.
1
23
24#ifndef BENCH_TIMER_H
25#define BENCH_TIMER_H
26
27#include <Arduino.h>
28
29namespace BenchTimer
30{
31inline volatile uint16_t overflows{ 0 };
32inline uint8_t savedTimsk0{ 0 };
33inline uint32_t overhead{ 0 };
34inline bool calibrated{ false };
35
37inline void begin()
38{
39 Serial.flush(); // no transmit interrupt during the measurement
40 savedTimsk0 = TIMSK0;
41 TIMSK0 = 0; // millis() paused
42 TCCR1B = 0;
43 TCCR1A = 0;
44 TCNT1 = 0;
45 overflows = 0;
46 TIFR1 = _BV(TOV1); // no stale overflow
47 TIMSK1 = _BV(TOIE1);
48 TCCR1B = _BV(CS10); // CPU clock, no prescaler
49}
50
52inline uint32_t end()
53{
54 const uint8_t sreg{ SREG };
55 cli();
56 // read while counting: once stopped, simavr reads TCNT1 as 0
57 const uint16_t low{ TCNT1 };
58 uint16_t high{ overflows };
59 if ((TIFR1 & _BV(TOV1)) && low < 0x8000U)
60 {
61 ++high; // overflow between the last interrupt and the read, not served yet
62 }
63 TCCR1B = 0;
64 TIMSK1 = 0;
65 TIFR1 = _BV(TOV1);
66 TIMSK0 = savedTimsk0;
67 SREG = sreg;
68 return (static_cast< uint32_t >(high) << 16) | low;
69}
70
72inline void start()
73{
74 if (!calibrated)
75 {
76 calibrated = true;
77 begin();
78 overhead = end();
79 }
80 begin();
81}
82
84inline uint32_t stop()
85{
86 return end() - overhead;
87}
88} // namespace BenchTimer
89
90ISR(TIMER1_OVF_vect)
91{
93}
94
95#endif // BENCH_TIMER_H
ISR(TIMER1_OVF_vect)
Definition bench_timer.h:90
volatile uint16_t overflows
Definition bench_timer.h:31
uint32_t end()
The cycles since begin(), its own instructions included.
Definition bench_timer.h:52
void start()
Starts a measurement (the first one also measures the overhead).
Definition bench_timer.h:72
uint32_t stop()
The CPU cycles since start(), without those of start() and stop().
Definition bench_timer.h:84
bool calibrated
Definition bench_timer.h:34
uint8_t savedTimsk0
Definition bench_timer.h:32
uint32_t overhead
Definition bench_timer.h:33
void begin()
Starts counting: from the last instruction on, one count per CPU cycle.
Definition bench_timer.h:37