Performance: approach of reducing loops
{ Please fit your text in 70 columns or so. -mod }
Hi,
For prototyping and for design of algorithms I like to use python and
there you
can use generators. However the generator mechanism is the reason for
comparing
two simple test implementations of loops and I would like to know
wether it's possible
to ensure equal execution time (more or less)...
Note: it's just simple test code for quick evaluation!
This first example is simply using two loops for creating pairs; when
limit is 5
you will get "(1, 2) (1, 3) (1, 4) (1, 5) (2, 3) (2, 4) (2, 5) (3, 4)
(3, 5) (4, 5)"!
- - -
typedef std::pair<int, int> Pair;
typedef std::set<Pair> PairSet;
void gen1(PairSet& pairs, const int limit)
{
int a, b;
for (a = 1; a <= limit; ++a)
for (b = a+1; b <= limit; ++b)
pairs.insert(std::make_pair(a,b));
}
- - -
Now the second approch:
- - -
void gen2(PairSet& pairs, const int limit)
{
PairIterator it(limit);
while (it) pairs.insert(it.key());
}
- - -
Executing the two functions (different sets of course) I get
following time results:
took 1.560 seconds (gen1).
took 3.580 seconds (gen2).
1999000 elements
Again: I would like to know wether it's possible to make a singificant
improvement to the second time.
My (test) implementation for the iterator:
- - -
struct PairIterator
{
PairIterator(const int limit)
: _limit(limit), _pair(1,1) /*_a(1), _b(1)*/ {}
inline operator bool ()
{
if (_pair.second == _limit) //_b == _limit)
{
++_pair.first; //++_a;
_pair.second = _pair.first + 1; //_b = _a + 1;
}
else ++_pair.second; //++_b;
return _pair.second <= _limit; //_b <= _limit;
}
inline const Pair& key() const
{ return _pair; }
int _limit;
Pair _pair;
// int _a;
// int _b;
};
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]