直接从 COLEDateTime 获取年份和月份还是先转换为 SYSTEMTIME 更快

Is it faster to get year and month directly from COleDateTime or converting to SYSTEMTIME first?

本文关键字:转换 更快 SYSTEMTIME COLEDateTime 获取 取年份      更新时间:2023-10-16

我想从 COLEDateTime 对象获取年份和月份,我希望它尽可能快。我有 2 个选择;

COleDateTime my_date_time;
int year = my_date_time.GetYear();
int month = my_date_time.GetMonth();

COleDateTime my_date_time;
SYSTEMTIME mydt_as_systemtime;
my_date_time.GetAsSystemTime(mydt_as_systemtime);
int year = mydt_as_systemtime.wYear;
int month = mydt_as_systemtime.wMonth;

问题是,哪个会更快?

COleDateTime将其内部日期表示形式存储为 DATE typedef,因此当您调用 GetYear()GetMonth()时,它每次都必须计算这些。在SYSTEMTIME情况下,wYearwMonth 的值存储为 DWORD s,因此这只是检索值的情况,但将COleDateTime转换为SYSTEMTIME会产生开销。

谢谢

斯特伦

多亏了@MarkRansom正确的方向,我找到了COLEDateTime的源代码。以下是功能;

ATLCOMTIME_INLINE int COleDateTime::GetYear() const throw()
{
    SYSTEMTIME st;
    return GetAsSystemTime(st) ? st.wYear : error;
}
ATLCOMTIME_INLINE int COleDateTime::GetMonth() const throw()
{
    SYSTEMTIME st;
    return GetAsSystemTime(st) ? st.wMonth : error;
}

所以COleDateTime::GetYear()无论如何::GetMonth()转换为SYSTEMTIME

由于这些是内联函数,因此这些将在呼叫站点就位。由于这些函数之间的GetAsSystemTime(st)是通用的,编译器优化应该将其分解为一个临时变量,因此我的 qestion 中的两个代码片段是等效的。由于选项 1 更简单,因此没有理由不这样做。


更新:

一旦我有机会,我就对代码进行了基准测试。看起来我所说的编译器优化不适用于上述代码。这两种方法的 100 万次操作的计时如下;

直拨:154ms
系统时间方法:75ms

好吧,这就解决了。转换为SYSTEMTIME它。