开发者

C++ Timestamps. Updating output

I am making a program in C++ and I wish to print the time at the start and end of the program execution. I have used the following code in main() to output the timestamp at the begining but the values do not update for the end of the program.

I am currently just working procedurally but I am thinking maybe a function would benefit me here.

int main(int argc, char **argv) {
  time_t now;
  struct tm *current;
  now = time(0);
  current = localtime(&now);
  cout <<"Examination began at: " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec开发者_Python百科 << endl;

  //program execution....

  cout <<"Examination ended at: " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;

  cout << "PROGRAM END++++++++++++++++++++++++++++++++++" << endl;

  return 0;
}

I understand from running the program that it is just using the same values the second time round, how would I go about making this a function?


The value of the 'current' time function is only set with a call to localtime(). The reason you're seeing the same value at the beginning and end of the program is because you've only called that function once. Reset the value of 'now' to time(0), and 'current' to the value of localtime(&now) after program execution, and you'll see the desired update.


To get the time at exit, you just need to repeat the calls to time and localtime.

int main(int argc, char **argv) {
  time_t now;
  struct tm *current;
  now = time(0);
  current = localtime(&now);
  cout <<"Examination began at: " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;

  //program execution....

  now = time(0);
  current = localtime(&now);
  cout <<"Examination ended at: " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;
  cout << "PROGRAM END++++++++++++++++++++++++++++++++++" << endl;

  return 0;
}

You asked about making this a function. I'm not sure that you need to, but if you want to, it might look like this:

void write_timestamp(std::ostream& o, const char *when) {
  time_t now;
  struct tm *current;
  now = time(0);
  current = localtime(&now);
  o << when << ": " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;
}

int main(int argc, char **argv) {
  write_timestamp(cout, "Examination began at");

  //program execution....

  write_timestamp(cout, "Examination ended at");
  cout << "PROGRAM END++++++++++++++++++++++++++++++++++" << endl;
  return 0;
}

localtime only has a one-second resolution, so as @littleadv points out, you would get more accurate results using clock, getrusage, or times. Or, since you're using C++, you might find Boost.Timer useful.


You can get better results by using functions like clock, getrusage or times. Read about these functions here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜