STLplus C++ Library Collection - subsystems/timer.hpp - A CPU Timer
Author: Andy Rushton

# STLplus C++ Library Collection

Website Collection Library

# subsystems/timer.hpp
A CPU Timer

- Browse Header timer.hpp
- Introduction
- Interface
- Usage

## Introduction

This component is a class which can be used to keep track of both CPU and elapsed time for a program or a part of a program. The idea is that you can create a timer object at any place in the code. That object can then be used to print the CPU time and elapsed time since the object was created.

## Interface

    class timer
    {
    public:
      timer(void);
      ~timer(void);

      void reset(void);

      float elapsed(void);
      float cpu(void);
      std::string text(void);
    };

The constructor records the current CPU and elapsed time at the point of construction of the object. At any subsequent time, the difference between the current time and the construction time can be retrieved using either the elapsed() function or the cpu() function. These functions return a float that represents the time in seconds. It is recommended that the format "%4.2f" is used to print these times.

Alternatively, a pre-formatted string representation of the two times can be retrieved using the text() function. This has the format:

    2.41s CPU, 2s elapsed

At present, the elapsed time is to the nearest second, whilst the CPU time is platform dependent but typically in hundredths or thousandths of a second.

The internal timers can be reset to zero by calling the reset method.

## Usage

To measure the time taken for a program to run, place the timer object declaration at the start of the program and the report at the end:

    int main(int argc, char* argv[])
    {
      timer main_timer;

      <do interesting things>

      std::cout << "run time: " << main_timer.text() << std::endl;
      return status;
    }

To time different sections of a program, use multiple timers:

    int main(int argc, char* argv[])
    {
      timer main_timer;

      timer phase1_timer;
      <do phase1>
      std::cout << "phase1: " << phase1_timer.text() << std::endl;

      timer phase2_timer;
      <do phase2>
      std::cout << "phase2: " << phase2_timer.text() << std::endl;

      std::cout << "run time: " << main_timer.text() << std::endl;
      return status;
    }