memmove | naive | memcpy |
---|---|---|
1.127516 | 2.276486 | 1.761408 |
1.682012 | 2.341650 | 1.603680 |
1.693679 | 2.220025 | 1.688858 |
Last active
April 20, 2019 18:00
-
-
Save rexim/65a25e1acec7a17113a4fd472f481c13 to your computer and use it in GitHub Desktop.
Delete array element benchmarking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <time.h> | |
#define N (1000 * 1000) | |
void array_print(int *xs, int n) | |
{ | |
for (int i = 0; i < n; ++i) { | |
printf("%d ", xs[i]); | |
} | |
printf("\n"); | |
} | |
void array_init(int *xs, int n) | |
{ | |
for (int i = 0; i < N; ++i) { | |
xs[i] = i; | |
} | |
} | |
void array_remove_naive(int *xs, int n, int i) | |
{ | |
assert(i < n); | |
for (int j = i; j < n - 1; ++j) { | |
xs[j] = xs[j + 1]; | |
} | |
} | |
void array_remove_memmove(int *xs, int n, int i) | |
{ | |
assert(i < n); | |
memmove(xs + i, xs + i + 1, sizeof(int) * (n - i - 1)); | |
} | |
void array_remove_memcpy(int *xs, int n, int i) | |
{ | |
assert(i < n); | |
memcpy(xs + i, xs + i + 1, sizeof(int) * (n - i - 1)); | |
} | |
int array_verify(int *xs, int n, int i) | |
{ | |
assert(i < n); | |
for (int j = 0; j < i; ++j) { | |
if (xs[j] != j) { | |
return 0; | |
} | |
} | |
for (int j = i; j < n; ++j) { | |
if (xs[j] != j + 1) { | |
return 0; | |
} | |
} | |
return 1; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int *xs = malloc(sizeof(int) * N); | |
clock_t result = 0; | |
for (int i = 0; i < 1000; ++i) { | |
array_init(xs, N); | |
clock_t start = clock(); | |
array_remove_memcpy(xs, N, i % N); | |
clock_t end = clock(); | |
result += end - start; | |
if (!array_verify(xs, N - 1, i % N)) { | |
printf("Array is not correct\n"); | |
// array_print(xs, N - 1); | |
return -1; | |
} | |
} | |
printf("%f\n", (double) result / CLOCKS_PER_SEC); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment