NetBurner 3.5.6
PDF Version
StopWatch Class Reference

High-resolution stopwatch timer for precise event timing and performance measurement. More...

#include <stopwatch.h>

Public Member Functions

 StopWatch (int timer_number=FIRST_UNUSED_TIMER)
 Construct a stopwatch object with optional timer selection.
 
void Start (bool clear_count=false)
 Start or resume the stopwatch timer.
 
void Clear ()
 Clear the accumulated elapsed time.
 
unsigned long long Stop ()
 Stop the stopwatch and return elapsed time.
 
unsigned long long GetTime ()
 Get the current elapsed time without stopping the timer.
 
double CountResolution ()
 Get the resolution of a single timer tick in seconds.
 
double Convert (unsigned long long ticks)
 Convert timer ticks to seconds.
 

Detailed Description

High-resolution stopwatch timer for precise event timing and performance measurement.

The StopWatch class provides a hardware-based timer interface for measuring time intervals with resolution far exceeding the RTOS tick rate. It is ideal for performance profiling, timeout detection, and precise event timing.

The stopwatch operates in two states:

  • Running: Timer is actively counting elapsed time
  • Stopped: Timer preserves elapsed time but does not increment

Time accumulates across multiple Start/Stop cycles unless explicitly cleared, making it useful for measuring cumulative execution time across multiple code sections or function calls.

Thread Safety

StopWatch objects are not inherently thread-safe. If multiple tasks need to access the same StopWatch, appropriate synchronization (mutexes, semaphores) must be used to prevent race conditions.

Timer Allocation

On most platforms, hardware timers are automatically allocated. Some older platforms may require explicit timer number specification via the constructor.

Note
The internal time representation uses unsigned long long to prevent overflow for extended timing periods, supporting timing intervals of years without rollover on typical hardware.

Constructor & Destructor Documentation

◆ StopWatch()

StopWatch::StopWatch ( int timer_number = FIRST_UNUSED_TIMER)

Construct a stopwatch object with optional timer selection.

Creates a new StopWatch instance and allocates a hardware timer for timing operations. On modern platforms with dedicated RTOS timers, the timer_number parameter can be omitted and the system will automatically select an available timer resource.

The stopwatch is created in a stopped state with zero elapsed time. Call Start() to begin timing.

Parameters
timer_numberOptional timer resource identifier. Use FIRST_UNUSED_TIMER (default) for automatic allocation, or specify a specific timer number if your platform requires explicit timer selection. Valid timer numbers are platform-dependent.
Note
After construction, the stopwatch is in a stopped state with GetTime() returning 0 until Start() is called.
Warning
On platforms with limited timer resources, ensure you don't create more StopWatch instances than available hardware timers. Check your platform documentation for timer availability.

Example:

StopWatch timer1; // Automatic timer allocation
StopWatch timer2(FIRST_UNUSED_TIMER); // Explicit automatic allocation
StopWatch timer3(2); // Use specific timer #2 (platform-dependent)
High-resolution stopwatch timer for precise event timing and performance measurement.
Definition stopwatch.h:138

Member Function Documentation

◆ Clear()

void StopWatch::Clear ( )

Clear the accumulated elapsed time.

Resets the stopwatch's elapsed time counter to zero. If the stopwatch is currently running, it continues running but from a zero starting point. If stopped, the elapsed time is simply cleared.

This is equivalent to calling Start(true) but works whether the stopwatch is running or stopped.

Note
After calling Clear(), GetTime() will return 0 until time accumulates.
This function does not change the running/stopped state of the stopwatch.

Example:

StopWatch timer;
timer.Start();
DoWork();
timer.Stop();
printf("First measurement: %llu\n", timer.GetTime());
timer.Clear(); // Reset to zero
timer.Start();
DoMoreWork();
timer.Stop();
printf("Second measurement: %llu\n", timer.GetTime());
See also
Start()
Stop()

◆ Convert()

double StopWatch::Convert ( unsigned long long ticks)

Convert timer ticks to seconds.

Converts a time interval or elapsed time value from hardware timer ticks (as returned by Stop() or GetTime()) to seconds as a double precision floating point number. This provides a human-readable representation of the measured time.

The conversion accounts for the platform's timer frequency and provides accurate time representation suitable for display, logging, or mathematical operations requiring time in standard units.

Parameters
ticksThe time value in hardware timer ticks to convert. This is typically obtained from Stop() or GetTime().
Returns
The equivalent time in seconds as a double precision floating point number. The precision depends on the timer resolution (see CountResolution()).
Note
The input value should be a tick count from this StopWatch instance. Tick values from other timers or sources may have different meanings.
The conversion is: seconds = ticks x CountResolution()
For very long timing intervals (hours/days), be aware of floating point precision limitations in the double type, though this is rarely an issue in practice for timing applications.

Example - Basic conversion:

StopWatch timer;
timer.Start();
PerformOperation();
unsigned long long ticks = timer.Stop();
double seconds = timer.Convert(ticks);
printf("Operation took %f seconds\n", seconds);

Example - Display in multiple units:

StopWatch timer;
timer.Start();
DoWork();
unsigned long long ticks = timer.Stop();
double seconds = timer.Convert(ticks);
double milliseconds = seconds * 1000.0;
double microseconds = seconds * 1000000.0;
printf("Elapsed time:\n");
printf(" %f seconds\n", seconds);
printf(" %f milliseconds\n", milliseconds);
printf(" %f microseconds\n", microseconds);
printf(" %llu ticks\n", ticks);

Example - Performance comparison:

StopWatch timer;
timer.Start();
Method1();
unsigned long long time1 = timer.Stop();
timer.Start(true); // Clear and restart
Method2();
unsigned long long time2 = timer.Stop();
double seconds1 = timer.Convert(time1);
double seconds2 = timer.Convert(time2);
printf("Method1: %f seconds\n", seconds1);
printf("Method2: %f seconds\n", seconds2);
if (seconds1 < seconds2)
printf("Method1 is %.2fx faster\n", seconds2 / seconds1);
else
printf("Method2 is %.2fx faster\n", seconds1 / seconds2);

Example - Throughput calculation:

StopWatch timer;
int itemsProcessed = 1000000;
timer.Start();
for (int i = 0; i < itemsProcessed; i++)
ProcessItem(i);
unsigned long long ticks = timer.Stop();
double seconds = timer.Convert(ticks);
double itemsPerSecond = itemsProcessed / seconds;
double secondsPerItem = seconds / itemsProcessed;
printf("Processed %d items in %f seconds\n", itemsProcessed, seconds);
printf("Throughput: %.2f items/second\n", itemsPerSecond);
printf("Average: %e seconds/item\n", secondsPerItem);
See also
Stop()
GetTime()
CountResolution()

◆ CountResolution()

double StopWatch::CountResolution ( )

Get the resolution of a single timer tick in seconds.

Returns the time value of one hardware timer tick, expressed as a double precision floating point number in seconds. This represents the finest granularity at which the stopwatch can measure time.

The resolution depends on the hardware timer frequency and typically ranges from nanoseconds to microseconds on NetBurner platforms. Higher resolution (smaller tick duration) provides more precise timing measurements.

Returns
The duration of one timer tick in seconds as a double. For example, a return value of 0.000001 indicates 1 microsecond resolution, while 0.000000001 indicates 1 nanosecond resolution.
Note
This value is constant for a given platform and timer configuration.
The resolution represents the theoretical precision; actual measurement accuracy may be affected by interrupt latency and system load.

Example - Display timer characteristics:

StopWatch timer;
double resolution = timer.CountResolution();
printf("Stopwatch timer resolution:\n");
printf(" Per tick: %e seconds\n", resolution);
printf(" Per tick: %f microseconds\n", resolution * 1e6);
printf(" Per tick: %f nanoseconds\n", resolution * 1e9);

Example - Calculate measurement precision:

StopWatch timer;
double resolution = timer.CountResolution();
timer.Start();
QuickOperation();
unsigned long long ticks = timer.Stop();
double time = timer.Convert(ticks);
double precision = resolution;
printf("Measured time: %f +/- %f seconds\n", time, precision);

Example - Validate timing requirements:

StopWatch timer;
double resolution = timer.CountResolution();
double required_precision = 0.000001; // 1 microsecond
if (resolution > required_precision)
{
printf("Warning: Timer resolution (%e s) is insufficient\n", resolution);
printf("Required: %e s\n", required_precision);
}
else
{
printf("Timer resolution (%e s) is adequate\n", resolution);
}
See also
Convert()
GetTime()

◆ GetTime()

unsigned long long StopWatch::GetTime ( )

Get the current elapsed time without stopping the timer.

Returns the current accumulated elapsed time in hardware timer ticks. Unlike Stop(), this function does not change the state of the stopwatch - if the timer is running, it continues running; if stopped, it remains stopped.

This is particularly useful for checking progress during long operations, implementing timeouts, or monitoring timing without interrupting the measurement.

Returns
The current accumulated elapsed time in hardware timer ticks. If the stopwatch is running, this includes time up to the moment of the call. If stopped, this returns the time at which Stop() was called. Use Convert() to convert this value to seconds.
Note
This function can be called while the timer is running or stopped.
The returned value is in hardware timer ticks. Use Convert() to convert to seconds or other time units.
On running timers, consecutive calls to GetTime() will return increasing values. On stopped timers, consecutive calls return the same value.

Example - Check progress without stopping:

StopWatch timer;
timer.Start();
while (ProcessingData())
{
// Check time periodically without stopping
double elapsed = timer.Convert(timer.GetTime());
if (elapsed > MAX_ALLOWED_SECONDS)
{
printf("Warning: Operation exceeding time limit!\n");
break;
}
}
timer.Stop();

Example - Timeout implementation:

StopWatch timer;
timer.Start();
while (!OperationComplete())
{
DoWork();
if (timer.Convert(timer.GetTime()) > TIMEOUT_SECONDS)
{
printf("Operation timed out!\n");
return ERROR_TIMEOUT;
}
}
timer.Stop();
return SUCCESS;

Example - Progress reporting:

StopWatch timer;
timer.Start();
for (int i = 0; i < totalItems; i++)
{
ProcessItem(i);
if (i % 100 == 0)
{
double elapsed = timer.Convert(timer.GetTime());
printf("Processed %d items in %.2f seconds\n", i, elapsed);
}
}
timer.Stop();
See also
Stop()
Start()
Convert()

◆ Start()

void StopWatch::Start ( bool clear_count = false)

Start or resume the stopwatch timer.

Begins timing from the current moment. If the stopwatch was previously stopped, it will continue accumulating time from the last elapsed value unless clear_count is true. This allows for cumulative timing across multiple Start/Stop cycles.

If called when the stopwatch is already running, this function has no effect unless clear_count is true, in which case it restarts timing from zero.

Parameters
clear_countIf true, resets the elapsed time to zero before starting. If false (default), continues accumulating time from the previous elapsed value, enabling cumulative timing.
Note
Calling Start() multiple times without stopping has no effect unless clear_count is true.
This function uses hardware timer reads and is very fast (typically < 1 microsecond overhead).

Example - Basic timing:

StopWatch timer;
timer.Start();
PerformOperation();
timer.Stop();

Example - Cumulative timing:

StopWatch timer;
timer.Start();
Operation1();
timer.Stop();
// Continue timing - adds to previous elapsed time
timer.Start();
Operation2();
timer.Stop();
// Total time for both operations
double total = timer.Convert(timer.GetTime());

Example - Restart from zero:

StopWatch timer;
timer.Start();
FirstMeasurement();
timer.Stop();
// Start fresh measurement
timer.Start(true); // Clear previous time
SecondMeasurement();
timer.Stop();
See also
Stop()
Clear()
GetTime()

◆ Stop()

unsigned long long StopWatch::Stop ( )

Stop the stopwatch and return elapsed time.

Stops the stopwatch timer and returns the total accumulated elapsed time in hardware timer ticks. The elapsed time is preserved and will continue to accumulate if Start() is called again without clearing.

If the stopwatch is already stopped, this function simply returns the current elapsed time without modifying the stopwatch state.

Returns
The total accumulated elapsed time in hardware timer ticks since the stopwatch was started (or last cleared). Use Convert() to convert this value to seconds.
Note
The returned value is in hardware timer ticks, not seconds. Use Convert() to convert to human-readable time units.
Calling Stop() multiple times returns the same value until Start() is called again.

Example - Basic stop and convert:

StopWatch timer;
timer.Start();
PerformOperation();
unsigned long long ticks = timer.Stop();
double seconds = timer.Convert(ticks);
printf("Operation took %f seconds (%llu ticks)\n", seconds, ticks);

Example - Multiple stop calls:

StopWatch timer;
timer.Start();
DoWork();
unsigned long long time1 = timer.Stop(); // Stops and gets time
unsigned long long time2 = timer.Stop(); // Same value as time1
// time1 == time2
See also
Start()
GetTime()
Convert()

The documentation for this class was generated from the following file: