# Boost :

Subject: [boost] [DateTime] dividing a time_period in N time_periods
Date: 2014-10-02 09:09:21

Hi, I want to make a method which divides a time_period in N time periods,
something like this:

list<time_period> splitTimePeriod(time_period timePeriod, int n);

I actually have made it and although it seems to work it results very
inefficient regarding the time it took to divide a large time_period.

The method I did is this:

list<time_period> splitTimePeriod(time_period timePeriod, int n)
{
double secsTime = dateTime::diffSeconds(timePeriod.end(),
timePeriod.begin());

// tiempo en segundos de cada perÃ­odo de tiempo
double ti = secsTime / n;

list<time_period> timePeriods;

// tiempo de comienzo del primer perÃ­odo de tiempo
ptime tpBegin = timePeriod.begin();

// tiempo de fin del Ãºltimo perÃ­odo de tiempo
ptime tpLastEnd = timePeriod.end();

for (int i = 0; i < n; i++)
{
int tUnits = ti * time_duration::ticks_per_second();

// tiempo de comienzo del siguiente perÃ­odo de tiempo
ptime tpNextBegin = dateTime::increment(tpBegin, tUnits);

// tiempo de fin del perÃ­odo de tiempo
ptime tpEnd;

if (i == n - 1)
{
tpEnd = tpLastEnd;
}
else
{
tpEnd = dateTime::decrement(tpNextBegin, 1);

// guarda para evitar que por cuestiones
// de redondeo, el tiempo final de un perÃ­odo
// sea mayor que el pasado inicialmente
if (tpEnd > tpLastEnd)
{
tpEnd = tpLastEnd;
}
}

time_period p(tpBegin, tpEnd);

// se inserta perÃ­odo de tiempo en la lista
timePeriods.push_back(p);

// se actualiza el comienzo del siguiente perÃ­odo de tiempo
tpBegin = tpNextBegin;
}

return timePeriods;
}

Other methods I use are these:

double diffSeconds(const ptime &dateA, const ptime &dateB)
{
time_duration diff = dateA - dateB;
return diff.total_seconds();
}

ptime increment(const ptime &date, int n)
{
time_iterator it(date, dateTime::unit);
for (int i = 0; i < n; i++)
{
++it;
}
return *it;
}

ptime decrement(const ptime &date, int n)
{
time_iterator it(date, dateTime::unit);
for (int i = 0; i < n; i++)
{
--it;
}
return *it;
}

const time_duration unit = microseconds(1);

#################################################
The question is: is there a better way to accomplish this?