Ok , consider this..
Code:
#include <iostream>
#include <time.h> // for clock()
#include <stddef.h> // for size_t
#include <string.h> // for memcpy()
using namespace std;
void copy_with_pointers(const char *src, char *dst, size_t n)
{
for (size_t k =0; k!=n; ++k)
*dst++ = *src++;
}
void copy_with_indices(const char *src, char *dst, size_t n)
{
for (size_t k =0; k!=n; ++k)
dst[k] = src[k];
}
int main()
{
const int n_bytes = 100000;
const int n_calls = 100;
const char *src = new char[n_bytes];
char *dst = new char[n_bytes];
// reduce paging effect by accessing all bytes:
memcpy(dst, src, n_bytes);
clock_t start, end, reftime;
// test 1 (reference time)
start = clock();
for (int k = 0; k!=n_calls; ++k)
memcpy(dst, src, n_bytes);
end = clock();
reftime = end - start;
// test 2 (pointers)
start = clock();
for (int k = 0; k!=n_calls; ++k)
copy_with_pointers(src, dst, n_bytes);
end = clock();
cout << "with pointers:" << static_cast<double>(end-start)/reftime << " times slowers then memcpy. \n";
// test 3 (indices)
start = clock();
for (int k = 0; k!=n_calls; ++k)
copy_with_indices(src, dst, n_bytes);
end = clock();
cout << "with indices:" << static_cast<double>(end-start)/reftime << " times slowers then memcpy. \n";
delete[] src;
delete[] dst;
return 0;
}
I've runned that code few times.. and i kept having different answers.
sometimes pointers were slowers sometimes indices were.
Shouldn't i get always the same timing?
Luigi
I use code warrior 7.0 on mac os X (10.2)
thx