的<ctime>替代品

Alternatives to <ctime>

本文关键字:替代品 gt ctime lt      更新时间:2023-10-16

我正在寻找<ctime>库的C++11版本。C++11中是否包含类似的内容?

编辑:任何有更多功能的东西都是完美的!

编辑2:我想把它用在我正在制作的游戏中,这样我就可以跟踪比赛的总时间。任何能帮助我的东西都是我想要的。

C++11包含<chrono>标头,它提供不同类型的时钟(我将使用高分辨率的时钟),具有now功能。你可以从now()中减去其中两个时间,得到它们之间<unit>的总数(我用秒):

using clock = std::chrono::high_resolution_clock;
using unit = std::chrono::seconds;
std::chrono::time_point<clock> startTime = clock::now(); //get starting time
... //do whatever stuff you have to do
std::chrono::time_point<clock> thisTime = clock::now();
long long secondsElapsed = std::chrono::duration_cast<unit>(thisTime - startTime).count();
//now use secondsElapsed however you wish
//you can also use other units, such as milliseconds or nanoseconds

但是,请注意,除非时钟的is_steady成员是true,否则不能保证secondsElapsed是正的,因为该成员是true意味着对now()的后续调用将给出比对now()的前一次调用更大的数字。

<ctime>中的许多函数,尤其是ctime函数本身,都与将日期和时间格式化为字符串有关。

C++11提供了一个新的io操作器std::put_time,它确实取代了C风格的函数,并且与C++的语言环境相关功能完全兼容。

具体来说,给定C样式tm格式的时间点:

std::time_t t = std::time(NULL);
std::tm tm = *std::localtime(&t);

如果使用特定于区域设置的格式参数,如%c(特定于区域的日期/时间)、%Ec(特定于地区的扩展日期/时间,如日本的英制年份)或%Z(时区),则std::put_time可根据任何选定的区域设置打印:

std::cout.imbue(std::locale("ja_JP.utf8"));
std::cout << "ja_JP: " << std::put_time(&tm, "%c %Z") << 'n';
std::cout << "ja_JP: " << std::put_time(&tm, "%Ec %Z") << 'n';

这些调用打印的内容类似:

2012年11月15日 11時49分04秒 JST     // first call
平成24年11月15日 10時49分05秒 JST   // second call

另一个答案中提到的来自<chrono>的时间点检索函数也可以使用to_time_t方法转换为tm结构,然后与put_time一起使用。这使得代码独立于任何C风格的函数调用,至少在表面上是这样:

using namespace std;
auto now = chrono::system_clock::now();
time_t now_c = chrono::system_clock::to_time_t(now);
cout << "Locale-specific time now: "
<< put_time(localtime(&now_c), "%c %Z") << 'n';

<chrono>持续时间类型相结合,在计算和打印日期和时间方面具有很大的灵活性:

time_t now_c = chrono::system_clock::to_time_t(now - chrono::hours(48));
cout << "Locale-specific time on the day before yesterday: "
<< put_time(localtime(&now_c), "%c %Z") << 'n';

这些是上面所有函数调用所需的标题:

#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>

可用性说明我不确定MSVC和Clang,但遗憾的是,GCC目前还没有提供std::put_time功能:http://gcc.gnu.org/bugzilla/show_bug.cgi?id=54354.