Skip to content

Instantly share code, notes, and snippets.

@rexim
Last active April 20, 2019 18:00
Show Gist options
  • Save rexim/65a25e1acec7a17113a4fd472f481c13 to your computer and use it in GitHub Desktop.
Save rexim/65a25e1acec7a17113a4fd472f481c13 to your computer and use it in GitHub Desktop.
Delete array element benchmarking
#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;
}
memmovenaivememcpy
1.1275162.2764861.761408
1.6820122.3416501.603680
1.6936792.2200251.688858
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment