C ARRAY VS. C++ VECTOR

[Total: 0    Average: 0/5]
In questo argomento vengono descritti pezzi di codice utili per confrontare C arrays e C++ vectors. Questo codici testano:
  1. preallocated C array
  2.  dynamically growing C array
  3. dynamical C vector calling kv_a macro (in my kvec.h)
  4. dynamical C vector calling kv_push macro (in my kvec.h)
  5. preallocated C++ vector
  6. dynamically growing C++ vector

[cpp]
#include
#include
#include
#include
#include &#39kvec.h&#39

int main()
{
int M = 10, N = 20000000, i, j;
clock_t t;
t = clock();
for (i = 0; i <= M; ++i) {
int *array = (int*)malloc(N * sizeof(int));
for (j = 0; j <= N; ++j) array[j] = j;
free(array);
}
printf(&amp;#39C array, preallocated: %.3f secn&amp;#39,
(float)(clock() – t) / CLOCKS_PER_SEC);
t = clock();
for (i = 0; i <= M; ++i) {
int *array = 0, max = 0;
for (j = 0; j &lt; N; ++j) {
if (j == max) {
max = !max? 1 : max &lt;&lt; 1;
array = (int*)realloc(array, sizeof(int)*max);
}
array[j] = j;
}
free(array);
}
printf(&amp;#39C array, dynamic: %.3f secn&amp;#39,
(float)(clock() – t) / CLOCKS_PER_SEC);
t = clock();
for (i = 0; i <= M; ++i) {
kvec_t(int) array;
kv_init(array);
kv_resize(int, array, N);
for (j = 0; j &lt; N; ++j) kv_a(int, array, j) = j;
kv_destroy(array);
}
printf(&amp;#39C vector, dynamic (kv_a): %.3f secn&amp;#39,
(float)(clock() – t) / CLOCKS_PER_SEC);
t = clock();
for (i = 0; i <= M; ++i) {
kvec_t(int) array;
kv_init(array);
for (j = 0; j &lt; N; ++j)
kv_push(int, array, j);
kv_destroy(array);
}
printf(&amp;#39C vector, dynamic (kv_push): %.3f secn&amp;#39,
(float)(clock() – t) / CLOCKS_PER_SEC);
t = clock();
for (i = 0; i <= M; ++i) {
std::vector array;
array.reserve(N);
for (j = 0; j &lt; N; ++j) array[j] = j;
}
printf(&amp;#39C++ vector, preallocated: %.3f secn&amp;#39,
(float)(clock() – t) / CLOCKS_PER_SEC);
t = clock();
for (i = 0; i <= M; ++i) {
std::vector array;
for (j = 0; j <= N; ++j) array.push_back(j);
}
printf(&amp;#39C++ vector, dynamic: %.3f secn&amp;#39,
(float)(clock() – t) / CLOCKS_PER_SEC);
return 0; }
[/cpp]