Skip to content

Instantly share code, notes, and snippets.

@weirddan455
Created September 20, 2022 00:26
Show Gist options
  • Save weirddan455/1352bb622dcd8eec7962d10c29d33939 to your computer and use it in GitHub Desktop.
Save weirddan455/1352bb622dcd8eec7962d10c29d33939 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#define ARRAY_SIZE 1000000
int compare(const void *a, const void *b)
{
int ia = *(int*)a;
int ib = *(int*)b;
return ia - ib;
}
int main(void)
{
FILE *unsorted = fopen("unsorted.txt", "r");
if (unsorted == NULL) {
puts("failed to open unsorted.txt");
return 1;
}
int *array = malloc(ARRAY_SIZE * sizeof(int));
if (array == NULL) {
puts("malloc failed");
return 1;
}
for (int i = 0; i < ARRAY_SIZE; i++) {
fscanf(unsorted, "%d", &array[i]);
}
fclose(unsorted);
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
qsort(array, ARRAY_SIZE, sizeof(int), compare);
clock_gettime(CLOCK_MONOTONIC, &end);
FILE *sorted = fopen("sorted.txt", "w");
for (int i = 0; i < ARRAY_SIZE; i++) {
fprintf(sorted, "%d\n", array[i]);
}
fclose(sorted);
free(array);
uint64_t nanoseconds = end.tv_sec - start.tv_sec;
nanoseconds *= 1000000000;
nanoseconds += end.tv_nsec - start.tv_nsec;
double miliseconds = (double)nanoseconds / 1000000.0;
printf("qsort took %fms\n", miliseconds);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment