【问题标题】:Get computer time c++ [duplicate]获取计算机时间c ++ [重复]
【发布时间】:2015-03-02 07:26:07
【问题描述】:

我正在使用 C++。我想获得计算机时间(我知道如何使用 ctime 函数)。我想像 int 变量(秒、分钟等)一样花时间。有什么帮助吗?

类似: int sec = get.sec(); int min = get.min();

我不想要 time_t 变量。

【问题讨论】:

  • 它可能是特定于操作系统的。
  • 您似乎没有进行任何研究。 // 关闭为重复。链接的问题有一些东西可以让你自纪元以来几秒钟。
  • 你搜索过c++ time吗?第一个链接是指向 (time)[cplusplus.com/reference/ctime/time/],并在底部引用了 (gmtime)[cplusplus.com/reference/ctime/gmtime/] 函数。看起来 tm 结构有你要找的东西。

标签: c++ time


【解决方案1】:

C++11 中,您可以使用<chrono>。您也可以使用time(2)localtime(3)strftime(3)clock(3)clock_gettime(2)(如果您的系统有它们)。可能

 time_t now=0;
 time(&now);
 char nowbuf[64];
 strftime(nowbuf, sizeof(nowbuf), "%c", localtime(now));

如果你想要一些字符串可能是相关的。否则,请注意 localtime 返回一个指向 struct tm 的指针,该指针具有许多数字字段。例如

struct tm* lt = localtime(now);
int hours = lt->tm_hour;
int minutes = lt->tm_min;

当然,原则上您应该需要针对timelocaltime 等的失败进行测试...(但我从来没有让这些函数失败过)。

详细信息通常是特定于操作系统的。如果在 Linux 上,请阅读 time(7);一些框架库,如 POCOQt 可能会在它们之上提供一个通用的(独立于操作系统的)抽象。

顺便说一句,您可能关心或不关心time zones,您可能想要gmtime 而不是localtime

【讨论】:

  • 嗯,是的,但我想要这样的东西: int sec = get.sec(); int min = get.min();
  • 现在,必须是一个结构 :)
  • struct 必须是什么? now(传递给time(&now) ...)被定义为time_t now=0;,是一个数字类型(我所知道的每个系统上的整数类型)。
  • int main() { time_t timer;结构 tm y2k;双秒; y2k.tm_hour = 0; y2k.tm_min = 0; y2k.tm_year = 100; y2k.tm_mon = 0; y2k.tm_mday = 1;时间(&定时器); /* 获取当前时间;等同于: timer = time(NULL) */ seconds = difftime(timer,mktime(&y2k)); printf("%.f 自 2000 年 1 月 1 日以来在当前时区的秒数", seconds);返回0; }
猜你喜欢
  • 2017-02-25
  • 1970-01-01
  • 2012-11-03
  • 2013-12-08
  • 2011-12-05
  • 2011-12-14
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
相关资源
最近更新 更多