95 lines
No EOL
2.2 KiB
C
95 lines
No EOL
2.2 KiB
C
/*-----------------------------------------------------------------------------
|
|
* HTBLA-Leonding / Class: 2IHIF
|
|
*-----------------------------------------------------------------------------
|
|
* Exercise Number: S05
|
|
* Title: Stopwatch
|
|
* Author: Marc Tismonar
|
|
*-----------------------------------------------------------------------------
|
|
* Description:
|
|
* Implementation of a simple stopwatch
|
|
*-----------------------------------------------------------------------------
|
|
*/
|
|
#include <time.h>
|
|
#include <stdbool.h>
|
|
|
|
#include "stopwatch.h"
|
|
|
|
/**
|
|
* Implementation hints:
|
|
*
|
|
* time functions:
|
|
* are provided by `time.h`
|
|
* use function `clock()` to get the current `ticks`
|
|
* `ticks` are of type `clock_t`
|
|
* use `CLOCKS_PER_SEC` to calculate the time in seconds from ticks
|
|
* -> seconds = ticks / CLOCK_PER_SEC
|
|
* microseconds are s * 10^-6
|
|
*/
|
|
|
|
static clock_t start_time = 0;
|
|
static clock_t passed_time = 0;
|
|
static bool is_active = false;
|
|
|
|
/**
|
|
* Starts taking the time. This function always starts at 0.
|
|
*/
|
|
void stopwatch_start()
|
|
{
|
|
start_time = clock();
|
|
passed_time = 0;
|
|
is_active = true;
|
|
}
|
|
|
|
/**
|
|
* Stops or pauses taking the time. Time measurement can be resumed
|
|
* via `stopwatch_resume`.
|
|
*/
|
|
void stopwatch_stop()
|
|
{
|
|
if (!is_active) {
|
|
return;
|
|
}
|
|
|
|
passed_time += clock() - start_time;
|
|
is_active = false;
|
|
}
|
|
|
|
/**
|
|
* Resumes taking the time. The previously measured time value is
|
|
* used as start value.
|
|
*/
|
|
void stopwatch_resume()
|
|
{
|
|
if (is_active) {
|
|
return;
|
|
}
|
|
|
|
start_time = clock();
|
|
is_active = true;
|
|
}
|
|
|
|
/**
|
|
* Determines whether or not the stopwatch takes the time.
|
|
* @return True if the stopwatch is measuring, false otherwise.
|
|
*/
|
|
bool stopwatch_is_active()
|
|
{
|
|
return is_active;
|
|
}
|
|
|
|
/**
|
|
* The measured time in microseconds.
|
|
*
|
|
* @return Either the processor time elapsed since start_stopwatch() has been called or
|
|
* the processor time elapsed between the calls of start_stopwatch() and stop_stopwatch().
|
|
*/
|
|
double stopwatch_get_elapsed_time()
|
|
{
|
|
clock_t total_time = passed_time;
|
|
|
|
if (is_active) {
|
|
total_time += clock() - start_time;
|
|
}
|
|
|
|
return ((double)total_time / CLOCKS_PER_SEC) * 1000000.0;
|
|
} |