1

I want to create a timer in C++ and when a user presses a button, the program logs to an array the name of the button pressed and the time it was pressed.

Later, I want to be able to 'play back' what the user has done, eg. starting a timer, and simulating the button presses at the correctly logged time in the array.

Where would the best place to start be? Is there a timer function in C++?

panthro
  • 22,779
  • 66
  • 183
  • 324

2 Answers2

1

You can do something like this

struct ButtonEvent{
     EventInfo ei;
     std::chrono::milliseconds time_stamp;

};

struct Recorder{
    std::chrono::steady_clock::time_point start_time_;


    std::deque<ButtonEvent> events_;

void StartRecording(){
    start_time_ = std::chrono::steady_clock::now();
}

    void HandleEvent(EventInfo e){
        ButtonEvent be;
        be.time_stamp = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() -  start_time_);
        be.ei = e;
        events_.push_back(be);
    }

    void Playback(){
        std::chrono::steady_clock::time_point 
        playback_time =std::chrono::steady_clock::now() ;
        while(events_.size()){
              std::chrono::milliseconds ts = 
                 std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - playback_time);
             if(events_.front().time_stamp <= ts){
             EventInfo e = events_.front().ei;
             // playback the event
             //...

             events_.pop_front();
        }

        // Some kind of sleep if you want

    }


}

};

Where EventInfo is some structure that has the info necessary to play back the event

John Bandela
  • 2,416
  • 12
  • 19
0

See the answer to How to get current time and date in C++? . The standard library for time in C++ is ctime which comes from C. As that answer mentions, use boost if you want a more modern date time API http://www.boost.org/doc/libs/1_52_0/doc/html/date_time/date_time_io.html

Community
  • 1
  • 1
JohnKlehm
  • 2,368
  • 15
  • 9