Skip to content

Instantly share code, notes, and snippets.

@SaveTheRbtz
Last active January 12, 2017 10:14
Show Gist options
  • Save SaveTheRbtz/5448488 to your computer and use it in GitHub Desktop.
Save SaveTheRbtz/5448488 to your computer and use it in GitHub Desktop.
Measure performance of qsort(3) vs std::sort()

C qsort(3) vs C++ std::sort()

On my hardware C++ sort implementation is almost three times faster than Mac OS X libc's:

λ ~/tmp/5448488/ master* make clean && make test
rm -f sort_cpp sort_c
${CXX:-c++} -std=c++11 -O3 sort.cpp -o sort_cpp
${CC:-cc} -O3 sort.c -o sort_c
./sort_cpp
Time: 11 seconds.
./sort_c
Time: 28 seconds.
CXX = $${CXX:-c++}
CXXFLAGS = -std=c++11 -O3
CC = $${CC:-cc}
CFLAGS = -O3
all: sort_cpp sort_c test
sort_cpp: sort.cpp
$(CXX) $(CXXFLAGS) $^ -o $@
sort_c: sort.c
$(CC) $(CFLAGS) $^ -o $@
test: sort_cpp sort_c
./sort_cpp
./sort_c
clean:
rm -f sort_cpp sort_c
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sysexits.h>
#define ARRAY_SZ 100000000
static int
int_cmp(const void *i1, const void *i2)
{
return *(int *)i1 - *(int *)i2;
}
int
main(void)
{
int i, *ints;
struct timeval t1, t2;
ints = malloc(ARRAY_SZ * sizeof(int));
if (ints == NULL)
exit(EX_TEMPFAIL);
for (i = 0; i < ARRAY_SZ; i++)
ints[i] = (int)random();
gettimeofday(&t1, NULL);
qsort(ints, ARRAY_SZ, sizeof(int), int_cmp);
gettimeofday(&t2, NULL);
printf("Time: %ld seconds.\n", t2.tv_sec - t1.tv_sec);
return EX_OK;
}
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>
int main() {
std::vector<int> ints;
std::time_t time;
for (int i = 0; i < 100000000; ++i)
ints.push_back(std::rand());
time = std::time(NULL);
std::sort(ints.begin(), ints.end(), std::greater<int>());
std::cout << "Time: " << std::time(NULL) - time
<< " seconds." << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment