C ++时间戳。更新输出

时间:2011-03-31 00:48:25

标签: c++

我正在用C ++编写程序,我希望在程序执行的开始和结束时打印时间。我在main()中使用了以下代码来输出开头的时间戳,但是值不会在程序结束时更新。

我目前只是在程序上工作,但我想也许一个功能会让我受益匪浅。

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....

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

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

  return 0;
}

我从运行程序中了解到它第二次使用相同的值,我将如何使其成为一个函数?

3 个答案:

答案 0 :(得分:1)

“当前”时间函数的值仅通过调用localtime()来设置。你在程序的开头和结尾看到相同值的原因是因为你只调用过一次这个函数。将'now'的值重置为time(0),然后 程序执行后,“当前”为localtime(&amp; now)的值,您将看到所需的更新。

答案 1 :(得分:0)

要在退出时获得时间,您只需重复拨打timelocaltime

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;
}

你问过这个功能。我不确定你是否需要,但如果你愿意,它可能看起来像这样:

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只有一秒的分辨率,因此@littleadv points out,您可以使用clockgetrusagetimes获得更准确的结果。或者,由于您使用的是C ++,因此您可能会发现Boost.Timer很有用。

答案 2 :(得分:-1)

使用clockgetrusagetimes等功能可以获得更好的效果。阅读这些函数here