的<ctime>替代品
Alternatives to <ctime>
我正在寻找<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.
- EASTL矢量<向量<int>>连续的
- C++中原子的替代品<variant>
- C++sscanf_s的替代品
- getline的替代品
- 什么是 std::function::argument_type 的替代品?
- 有DirectShow的替代品吗?
- 智能指针作为 QObject::d eleteLater() 的替代品
- C++中 mktime 的替代品
- 对于C++,是否有任何现代的 std::strchr() 替代品?
- shared_future是<void>condition_variable的合法替代品吗?
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- C 字符串比较“祝您好运”&gt;“再见”
- 这是山塔的替代品
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- STD :: Referent_wrapper/std :: std :: vector的selution_ptr替代品
- 更好的替代品?
- 排序向量上 std::find_if 和 std::bind2nd 的替代品
- 提升勒让德多项式的 gsl_sf_legendre_sphPlm_array() 替代品
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- C 操作员&gt;&gt;与突变器过载