Comparing dates, C++

Status
Not open for further replies.

blazko

Ars Scholae Palatinae
840
I need to compare dates with the presicion of a second. In high school we probably would have done something like...

code:<HR>
Code:
bool x_greaterthan_y(date x, date y)
{
  if(x.year > y.year) return 1;
  else if(x.year < y.year return 0;
       else /*they're the same year */
         if(x.month > y.month) return 1;
         //etc, etc, etc...
}

zzz... well I wrote a formula just to put everything in terms of seconds and then subtract.

code:<HR>
Code:
bool x_greaterthan_y(date x, date y)
{
  long int sx, sy;
  sx = x.year * 31536000 + x.day * 86400 + x.hour * 3600 + x.min * 60 + x.sec;
  sy = y.year * 31536000 + y.day * 86400 + y.hour * 3600 + y.min * 60 + y.sec;

  return ((sx - sy) > 0);
}

I would have had to use doubles in school because our compilers only supported 16bit integers, but at home I can have 32bit or even 64bit integers (although to my understanding CPU's are not yet optimized for dealing with 64bit ints). Basically what I'm asking is there any mentionable performance difference what so ever between the if-else, int, or double method of solving this? Worst case this function would probably only be called about 100 in a row.

Thanks for any input
-blazko
 
A routine like that is super-cheap, and hardly worth optimizing in most cases.

That being said, if you're testing for {>,==,<}, then your method is likely the fastest. However, if you were doing something a bit more subtle, like a comparison for {==,!=}, and you statistically expect most times to not be within a second of each other, you could probably do better with a nesting of ifs, from second up to year. Ifs in ASM are surprisingly short, and great for nested equality tests. But, in your case, since you need {>,==,<}, I'd say your solution is more or less ideal.
 

petrov

Ars Tribunus Militum
2,714
Your ratio of bugs to lines in your optimized version is approaching 1. :eek:
a) assuming that your ints (or longs) are 32 bits is a bad habit.
b) Even if you have 32 bit longs on your system, your "optimized" code will fail for dates with a year greater than 68. so if your dates start from 1900 (such as perl and MacOS does), or if they start from 1970 and you are writing for system that deals with the future (such as computing bank loans), this code is incorrect.
c) there aren't 31,536,000 seconds in a year, there are 31,557,600, as every year is actually 365.25 days long due to leap year (I believe it's actually 365.24, which is why we have goofy rules for leap years).
d) when you can, you should re-use code, especially when it's built into your system libraries. The system routines that will correctly give you seconds from a struct tm stucture (which is what your date type looks like) is mktime. Look up mktime(3) and difftime(3) in your system's manual, it should have a description of the struct tm as well.

In general, always write the correct code first, and then optimize the slow parts when you have a performance problem. Making local optimizations for speed early in the development cycle is a horrible idea.

--sam
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
Why aren't you using utilities in ctime (time_t, struct tm, mktime(), and difftime()) for this?

Lifted from H&S:

code:<HR>
Code:
#include <time.h> /* <ctime> for C++ */

double Secs_Since_Apr_15 (void)
{
    struct tm Apr_15_struct = {0};
    time_t Apr_15_t;
    Apr_15_struct.tm_year = 101; /* 2001 */
    Apr_15_struct.tm_mon = 3;
    Apr_15_struct.tm_day = 15;
    Apr_15_t = mktime (&Apr_15_struct);
    if (Apr_15_t == (time_t) -1)
    {
        return 0.0;
    }
    else
    {
        return difftime (time (NULL), Apr_15_t);
    }
}
 

htom

Ars Legatus Legionis
12,590
Subscriptor
The number of seconds in a year varies.

If you do not need the difference in times, and don't need to handle various calenders, it will usually be faster to compare the years, then the months, then the days, then the hours, then the seconds (modern pipelining may negate this claim.)

If you do need the difference in time, or handle calenders, convert each calender & date & location & time to Julian Day number and time, and compare those.
 

HL7

Ars Praefectus
3,523
Subscriptor++
Originally posted by blazko:
I would have had to use doubles in school because our compilers only supported 16bit integers, but at home I can have 32bit or even 64bit integers (although to my understanding CPU's are not yet optimized for dealing with 64bit ints). Basically what I'm asking is there any mentionable performance difference what so ever between the if-else, int, or double method of solving this? Worst case this function would probably only be called about 100 in a row.
It's already been pointed out that you ought to be looking into using difftime on a struct tm (there no reason to duplicate standard libraries if they'll work fine). But if for some reason you want to use your own time structure, the nested if method is faster. The multiple MUL operations will take _a lot_ more clock cycles than simple comparisons. Someone correct me if I'm wrong, but off the top of my head, I seem to remember a MUL on x86 taking ~40 cycles, and CMP taking ~2.

In any case, the nested-if method comes down to a bunch of MOV, CMP, Jxx, while the other one comes down to a bunch of MOV, ADD, MUL, CMP, and Jxx. It's obvious which one will be faster.

But in general, optimizing for every clock cycle doesn't matter unless you're writing something like a game where every cycle counts, or a program that does really intense calculations for a long time. Most programs spend > 90% of their time waiting on user input, and you're usually talking about the difference between calculating something in 0.9 seconds vs. 0.8.
 

htom

Ars Legatus Legionis
12,590
Subscriptor
Speed hints: don't do multiply if you're doing small integers, do shift & add (subtract) and document what you're doing.

60 * a =
(64 * a) - (4 * a) =
4 * ( (16 * a) - a) ; these multiplies can be done as shifts.

(A really bright compiler will do this for you! -- but might not try to factor 3600.)

And do the equal test first; if they are equal, you need to do more testing, if they're not, you can decide in one test. Doing (say) the greater test first, then the lesser, and falling through to equal (more) means you did two tests to get to do more, rather than one.
 

Midlands

Ars Praetorian
535
Subscriptor
Originally posted by blazko:
Thanks for any input
-blazko

Perhaps the best advice of all is that unless this is in a core inner loop of your program (that is, you're comparing literally millions of dates each second), it is beyond irrelevant how fast it is.

I know this has been said a zillion times -- and you may very well have this in an inner loop, in which case it might matter -- but premature optimization is the root of an amazing number of bugs.

Studies have been done showing that programmers are just astoundingly bad at guessing where the performance bottlenecks in their code are. Furthermore, a better algorithm (O(N^2) rather than O(2^N) or whatever) will completely dominate any of the sort of 'micro-level' optimizations you've got here.

I write code without remotely worrying about issues like these, and instead paying attention to the (surprisingly few) places where I am doing something with truly large collections of things (10,000 or more, typically) or doing something extremely often (1,000 times a second or more). I then use a profiler to show me the hot spots; they are very rarely where I think they are. If I'd spent time optimizing as I went along, I'd have a much slower and vastly buggier program.

So, again, I may be well off the mark here, because you may indeed have this in an inner loop. But if you don't, I'd suggest (a) making it correct first, (b) using a library function -- date and time functions will scramble your brain long before you get them correct in anything approaching most of the edge cases that are out there, and then (c) using a profiler.

The designer of the new language Arc had a very, very good point: it is almost totally irrelevant today if your compiler produces 'fast' code. What is vastly more important is whether you have a good profiler or not. A slow language with a good profiler you can speed up; a fast language with no profiler or a bad profiler will screw you every time.
 
I think "htom + HL7 = win". HL7's right about CMP operators being fast on the x86 (and every other) familiy of CPUs. 40 cycles for a MUL is a bit large though, for integer multiplications... remember, he has no floating point ops. Also, I must say that any good compiler should factor the multiplications and use shifts and adds. If this is the case, then the CMPs are coupled with JMPs etc for the nested IF statements, and become pretty comparable in terms of cost.

At the end of the day, though, I still bet that there's very little difference to either approach. Accessing memory in the first place will dominate any of the smaller operations that you choose to use for this simple routine. ;)
 

petrov

Ars Tribunus Militum
2,714
Originally posted by htom:
Speed hints: don't do multiply if you're doing small integers, do shift & add (subtract) and document what you're doing.

this is a bad idea. You should use unsigned math and let the compiler perform this optimizations. The compiler will only perform this optimization on unsigned math (which is the only time it's correct), so you rather than doing:
code:<HR>
Code:
int x, y;
x = y / 4;  // or the buggier x = y >> 2;

/* do this instead */
unsigned int x, y;
x = (unsigned int) y / 4;

I seriously doubt that there's very many optimizing compilers that can't convert between divisions and shifts, you just have to put the unsigned hints in there for it to use. I've tracked down bugs when people shift by the wrong amount or in the wrong direction. I've never tracked down a bug when a programmer meant to divide by 4 and actually divided by 8. Don't use shifts! let your compiler do it.

--sam
 

HL7

Ars Praefectus
3,523
Subscriptor++
Originally posted by euzeka:
While I don't know the exact numbers, I'm pretty sure that's not it. Even an FDIV will complete in under 40 cycles IIRC. A simple MUL is probably only 1 or 2 cycles. OTOH, a comparison involves a branch which can create pipeline nastyness...
I think I may be recalling the numbers for the 8088.
 

noppers

Ars Scholae Palatinae
1,156
Well, everyone has given you good advice here, but I just wanted to show you a method that is like yours except I think a little easier to program:

Instead of converting to seconds (which is arbitrary), just convert the multiple date numbers into one number that you can still read the date on. Basically you just multiply by factors of 10 so the numbers are shifted over and then you add them. Say you had year, month, and day, you would just do:
code:<HR>
Code:
 year*10000+month*100+day
and it would come out looking something like 20020228. You can extend this outward to include time also.

But anyway, there are better ways to compare the dates, such as those that have been mentioned. I just wanted to point out to you that converting to seconds is arbitrary and requires more thought than this method which will work just the same.
 

tam

Ars Scholae Palatinae
1,475
Why not compare the years, then compare the months, then the days, then the hours, minutes, and seconds? Why do you have to cook the data before doing your comparison? The benefit is that if the two dates are years apart, you only do one comparison.

code:<HR>
Code:
if (year1 > year2)
{
    return true;
}
else if (year1 < year2)
{
    return false;
}

if (month1 > month2)
{

}
 

tam

Ars Scholae Palatinae
1,475
Why not compare the years, then compare the months, then the days, then the hours, minutes, and seconds? Why do you have to cook the data before doing your comparison? The benefit is that if the two dates are years apart, you only do one comparison.

code:<HR>
Code:
if (year1 > year2)
{
    return true;
}
else if (year1 < year2)
{
    return false;
}

if (month1 > month2)
{
    return true;
}
else if (month1 < month2)
{
    return false;
}

... and so on ...

The downside is that it's a long-ass string of if{}elseif{} statements. But if you consider that you're going to be reading (possibly useless) data from memory/disk if you do a monstrous multiplication, this might be a benefit. (Assuming, of course, that reading from memory/disk is a far more complicated operation than multiplication and if/else constructs. This seems like a very safe assumption.) Another downside is that you've got a significantly larger function footprint to have to load into memory. But considering locality optimizations for memory operations, I think this is less of an issue.
 

HL7

Ars Praefectus
3,523
Subscriptor++
Originally posted by tam:
The downside is that it's a long-ass string of if{}elseif{} statements.

Well, you could always say

code:<HR>
Code:
return (year1 > year2) ? true : ((month1 > month2) ? true : ((day1 > day2) ? true : ((hour1 > hour2) ? true: ((min1 > min2) ? true : ((sec1 > sec2) ? true : false))))));

;)
 
Allow me to present date comparison mechanism #213098:

code:<HR>
Code:
if (x.year   != y.year)   return (x.year   > y.year);
if (x.month  != y.month)  return (x.month  > y.month);
if (x.day    != y.day)    return (x.day    > y.day);
if (x.hour   != y.hour)   return (x.hour   > y.hour);
if (x.minute != y.minute) return (x.minute > y.minute);
return (x.second > y.second);
 

htom

Ars Legatus Legionis
12,590
Subscriptor
Noop -- excellent.

For hms --> seconds, I'd like to see something like

code:<HR>
Code:
function hms2seconds(hours, minutes, seconds: typelike 0..int) returns 0..int
*** convert hours minutes seconds to total seconds
*** seconds + 60 * (minutes + 60 * hours) = seconds
*** 60*n == 4*(15*n) == 4*(16*n-n) use shifts & adds
*** 16*, shift 4; 4*, shift 2
t1 := minutes + (( hours << 4 - hours )) << 2)
return seconds + (( t1 << 4 - t1) << 2 )

excessively wordy, but when you're groggy and reading ten year old code in a language you're not comfy in, it all helps.
 
Status
Not open for further replies.