cpluspluscourse icon indicating copy to clipboard operation
cpluspluscourse copied to clipboard

Add a slide on timing commands

Open sponce opened this issue 4 years ago • 4 comments

as several exercises say "time ..." without details. Or maybe it's something to put in the "test" exercise with some explanations in the notes ?

This issue is replicated from the previous gitlab repo

sponce avatar Oct 22 '21 05:10 sponce

This is an easy simplification of a simple timer class I once wrote, is this what you meant?

#ifndef CPP_TIMER_H
#define CPP_TIMER_H 1

#include <chrono>

class Timer {

public:
  // other clocktypes to high_resolution_clock are steady_clock or system_clock
  // see https://www.modernescpp.com/index.php/the-three-clocks for details
  typedef std::chrono::high_resolution_clock CLOCKTYPE;

  // Constructor initialises with the current timestamp
  Timer() : m_StartTime(CLOCKTYPE::now()) {}

  // Destructor
  virtual ~Timer() {}

  // (Re-)start the clock by overwriting the starting timestamp
  void Start() { m_StartTime = CLOCKTYPE::now(); };

  // Return the duration in seconds
  float GetDuration() {
    std::chrono::duration<float> duration = CLOCKTYPE::now() - m_StartTime;
    return duration.count();
  };

private:
  // member to keep the starting timestamp
  CLOCKTYPE::time_point m_StartTime;
};

#endif // CPP_TIMER_H

with a simple usage example

#include "timer.h"
#include <iostream>
#include <unistd.h>

int main() {
  Timer timerinstance;
  sleep(1);
  float duration = timerinstance.GetDuration();
  std::cout << duration << std::endl;

  return 0;
}

roiser avatar Jan 17 '22 13:01 roiser

But also very useful:

/usr/bin/time ./executable
time ./executable

hageboeck avatar Jan 17 '22 13:01 hageboeck

yes, I wasn't sure to what detail we wanted to have it ...

roiser avatar Jan 17 '22 14:01 roiser

This issue or pull request has been automatically marked as stale because it has not had recent activity. Please manually close it, if it is no longer relevant, or ask for help or support to help getting it unstuck. Let me bring this to the attention of @klieret @wdconinc @michmx for now.

stale[bot] avatar Jul 19 '22 18:07 stale[bot]