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

StackOverflow https://stackoverflow.com/questions/10838193

Pergunta

I want to get the year and month from a COleDateTime object and I want it to be as fast as possible. I have 2 options;

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

or

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;

The question is, which would be faster?

COleDateTime stores it's internal date representation as a DATE typedef, and so when you call GetYear() and GetMonth() it has to calculate these each time. In the SYSTEMTIME case, the values of wYear and wMonth are stored as DWORDs so it is just a case of retrieving the values, but there is an overhead in converting a COleDateTime to a SYSTEMTIME.

Thanks,

Sterren

Foi útil?

Solução

Thanks to the point in the right direction @MarkRansom, I tracked down the source code for COleDateTime. Here are the functions;

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;
}

So COleDateTime::GetYear() and ::GetMonth() do the conversion to SYSTEMTIME anyway!

Since these are inline functions, these will be put in place at the call site. Since GetAsSystemTime(st) is common between these functions, compiler optimisation should factor out this into a temporary variable and therefore the two code snippets in my qestion are equivalent. Since option 1 is simpler, there is no reason not to go with that.


Update:

Once I got the opportunity, I benchmarked the code. It looks like the compiler optimisation I was talking about does not apply to the aforementioned code. The timings for 1 million operations of either method are as follows;

Direct calls: 154ms
SYSTEMTIME method: 75ms

Well that settles it. Conversion to SYSTEMTIME it is.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top