Comparing two times for equality within tolerance?
I have an MFC application where I want a certain method to be called at specified times. I will specify the times by using a vector of tm structs that have the hour minute and second filled out. Possibly I may need to store a boolean value for each time to indicate whether the method was called at the specified time. I have a timer that goes off every 50ms.
In MFC, the time is not guaranteed to go off at the specified interval. I want to ensure that the method is called even if off by a few seconds. My application does not currently require precise timing (although I'm open to it if there is an easy solution). My current thought on how to do this is to allow for some slippage such that I allow the time to be equal +/- a few seconds. Does that seem like a reasonable way to achieve this?
I want to check if two times are equal within a certain tolerance of seconds. What's the best way to to this in c++? I have access to a CTime object and/or a struct tm object (a开发者_JAVA百科nd potentially other windows time data structures)
UPDATE
I guess there is actually added complexity in the case where the seconds is near the minute or hour boundary. I can't just compare seconds.
You need to use mktime to get a time_t
. time_t
is generally the number of seconds since the beginning of 1970, so you don't need to worry about 2:10:59 vs 2:11:01.
struct tm expected_tm;
struct tm actual_tm;
// set those tms to something
time_t expected_time = mktime( &expected_tm );
time_t actual_time = mktime( &actual_tm );
if ( abs( expected_time - actual_time ) < 5 ) // for 5s tolerance
{
// GOOD
}
else
{
// BAD
}
精彩评论