Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Keeping track of how many seconds has passed since start of program

Tags:

c++

time

I am writing a program that will be used on a Solaris machine. I need a way of keeping track of how many seconds has passed since the start of the program. I'm talking very simple here. For example I would have an int seconds = 0; but how would I go about updating the seconds variable as each second passes?

It seems that some of the various time functions that I've looked at only work on Windows machines, so I'm just not sure.

Any suggestions would be appreciated.

Thanks for your time.

like image 688
Noob Avatar asked Nov 14 '09 19:11

Noob


3 Answers

A very simple method:

#include <time.h>
time_t start = time(0);

double seconds_since_start = difftime( time(0), start);

The main drawback to this is that you have to poll for the updates. You'll need platform support or some other lib/framework to do this on an event basis.

like image 189
Michael Burr Avatar answered Oct 24 '22 18:10

Michael Burr


Use std::chrono.

#include <chrono>
#include <iostream>

int main(int argc, char *argv[])
{
   auto start_time = std::chrono::high_resolution_clock::now();
   auto current_time = std::chrono::high_resolution_clock::now();

   std::cout << "Program has been running for " << std::chrono::duration_cast<std::chrono::seconds>(current_time - start_time).count() << " seconds" << std::endl;

   return 0;
}

If you only need a resolution of seconds, then std::steady_clock should be sufficient.

like image 41
Casper Beyer Avatar answered Oct 24 '22 19:10

Casper Beyer


You are approaching it backwards. Instead of having a variable you have to worry about updating every second, just initialize a variable on program start with the current time, and then whenever you need to know how many seconds have elapsed, you subtract the now current time from that initial time. Much less overhead that way, and no need to nurse some timing related variable update.

like image 38
prismofeverything Avatar answered Oct 24 '22 19:10

prismofeverything