1

我想从 COleDateTime 对象中获取年份和月份,并且希望它尽可能快。我有两个选择;

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将其内部日期表示存储为DATEtypedef,因此当您调用时GetYear()GetMonth()它必须每次都计算这些。在这种SYSTEMTIME情况下,wYearand的值wMonth存储为DWORDs ,因此这只是检索值的一种情况,但是将 a 转换COleDateTime为 a会产生开销SYSTEMTIME

谢谢,

斯特伦

4

1 回答 1

2

感谢@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)这些函数之间是通用的,编译器优化应该将其分解为一个临时变量,因此我的问题中的两个代码片段是等效的。由于选项 1 更简单,因此没有理由不使用它。


更新:

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

直接调用:154ms
SYSTEMTIME 方法:75ms

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

于 2012-06-01T08:42:59.177 回答