I thought about calling the loop with pointers to the [i] and [j] indexes,
to see if it would help. Sometimes it is faster, however, I've seen times be equal or a little slower.
Your test for 0.5 may be better if you took the absolute of i - j giving yourself a +/- 0.5 range to be considered equal.
Since using floating point you will need to use fabs (or is using abs ok in C++?).
I also tried a dabs which works out to be about the same speed as fabs.
edit: Just realized your equal weight test must be done first, then check for lesser or greater, otherwise you may be missing some lesser values that fall within the equal weight range.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
using namespace std;
double dabs(const double v)
{
return ( v < 0 ? v*-1.0 : v );
}
void loop1(const int M, const int i,const int j,double const dm[][1000] )
{
int less = 0, more = 0, equal = 0;
for (int k=0; k<M; k++)
{
//cout << "dm: " << j << " "<< k << " " << dm[j][k] << endl;
if ( fabs( dm[i][k] - dm[j][k] ) <= 0.5 )
equal++;
else if ( dm[i][k] < dm[j][k] )
less++;
else
more++;
}
cout << "Less: " << less
<< " More: " << more
<< " Equal: " << equal
<< endl;
}
void loop2(const int M, const double * arr1, const double * arr2)
{
int less = 0, more = 0, equal = 0;
for (int k=0; k<M; k++)
{
//cout << "a1: " << arr1[k] << " a2:"<< arr2[k] << endl;
if ( fabs( arr1[k] - arr2[k] ) <= 0.5 )
equal++;
else if ( arr1[k] < arr2[k] )
less++;
else
more++;
}
cout << "Less: " << less
<< " More: " << more
<< " Equal: " << equal
<< endl;
}
int main()
{
double dm[1000][1000];
int start;
int stop;
int Max = 500;
srand((unsigned)time(0)); // set seed
for (int i=0;i<1000;i++)
for (int j=0;j<1000;j++)
dm[i][j] = 1000 * rand() / (RAND_MAX + 1.0);
int iseq[10000];
int jseq[10000];
for (int x=0;x<10000;x++)
{
iseq[x] = int(rand()%1000);
jseq[x] = int(rand()%1000);
}
start = clock();
for (int x=0;x<10000;x++)
{
loop1(Max,iseq[x],jseq[x],dm);
}
stop = clock();
int total_time1 = stop - start;
start = clock();
for (int x=0;x<10000;x++)
{
loop2(Max,dm[iseq[x]],dm[jseq[x]]);
}
stop = clock();
int total_time2 = stop - start;
cout << "Time Loop1: " << total_time1 << endl;
cout << "Time Loop2: " << total_time2 << endl;
return 0;
}
|
Sample output:
Less: 270 More: 123 Equal: 107
Less: 232 More: 150 Equal: 118
Less: 244 More: 154 Equal: 102
Time Loop1: 60000
Time Loop2: 70000
Less: 239 More: 140 Equal: 121
Less: 261 More: 125 Equal: 114
Less: 232 More: 150 Equal: 118
Less: 254 More: 147 Equal: 99
Time Loop1: 70000
Time Loop2: 60000
Rich