timer_start()

Synopsis:

unsigned timer_start();

Description:

Read and return the hardware timer's current count value.

Timer functions in startup code

You use this function with timer_diff(), timer_ns2tick(), and timer_tick2ns() to provide the startup code with access to the hardware timer to perform the following tasks:
  • Measure how long an action takes.
  • Measure other hardware timers or obtain their characteristics. For example, to calculate cycles_per_sec for the qtime member of the system page, which characterizes the speed of the hardware timer used by ClockCycles().
  • Wait for a period of time.

Examples

The following code measures how long it takes to perform an action and converts the value to nanoseconds:

unsigned start = timer_start(); 
// Perform the action. 
unsigned num_hardware_timer_ticks = timer_diff(start);
unsigned long elapsed_time_in_ns = timer_tick2ns(num_hardware_timer_ticks);

The following code adds a waiting period measured in nanoseconds. To compare the specified waiting period to the value returned by timer_diff(), it converts the nanoseconds to hardware timer ticks:

unsigned timer_periods = timer_ns2tick(time_to_wait_in_ns);
const unsigned start = timer_start();
do {
	// nothing
} while(timer_diff(start) < timer_periods);

Timer reset

When you implement timer_start(), you can choose whether or not it resets the hardware timer each time you call it. For this reason, you cannot nest calls to timer_start() and timer_diff(). For example, the following code produces unexpected results:

// DO NOT DO THIS
unsigned start_overall = timer_start(); 			// Reset hardware timer.
for(unsigned i =0; i < NUM_THINGS; i++) { 
	unsigned start = timer_start(); 				// Reset hardware timer again. 
	// do stuff 
	unsigned diff = timer_diff(start); 
	// do more stuff
}
// do other stuff
unsigned diff_overall = timer_diff(start_overall); // Invalid value.

Interrupts

Because interrupts are not enabled until the kernel is running, they are disabled when these startup functions execute.

Returns:

A value in hardware timer ticks to pass to timer_diff().