0
My goal with this test would be to compare the speed performance between these two functions:
static inline void VectAssign1(int *const g , const int x , int n )
{
// g[ i ] = x for each i = 0 .. n - 1
for( int *tg = g + n ; tg > g ; )
*(--tg) = x;
}
static inline void VectAssign2(int *g , const int x , int n )
{
// g[ i ] = x for each i = 0 .. n - 1
for( int i = 0; i < n; i++ )
g[i] = x;
}
for that I rode the following:
int main() {
clock_t t;
const int n = 100000000;
int* v = new int[n];
int* w = new int[n];
t = clock();
VectAssign1(v,10,n);
t = clock() - t;
cout << ((float)t)/CLOCKS_PER_SEC << endl;
//print(v,n);
t = clock();
VectAssign2(v,10,n);
t = clock() - t;
cout << ((float)t)/CLOCKS_PER_SEC << endl;
//print(w,n);
return 0;
}
I sent the same vector v to the two functions, and the second time I overwrite the values of v again, and saw that the time and much higher on the first call:
- 1)0.387355
- 2)0.218332
To make it clearer I sent different vectors:
clock_t t;
const int n = 100000000;
int* v = new int[n];
int* w = new int[n];
t = clock();
VectAssign1(v,10,n);
t = clock() - t;
cout << ((float)t)/CLOCKS_PER_SEC << endl;
//print(v,n);
t = clock();
VectAssign2(w,10,n);
t = clock() - t;
cout << ((float)t)/CLOCKS_PER_SEC << endl;
//print(w,n);
return 0;
got the exits:
- 1)0.435841
- 2)0.436091
- Because calling the two functions with the same vector, the time of supersede for the second time is less?
- As we can see, with different vectors for each vector, and also by initiating the vectors for the first time, the performance of the two functions are identical. If one can answer, there is a preference for the first or second way to initialize the elements of a vector?
I didn’t even run a code analysis, but most likely the cache.
– Maniero
that’s right, processor cache, E, clock, when you start a loop process, your processor will take a while to "realize" that you need to increase frequency, gradually you will see this impact in the gradual increase of CPU usage
– anon