Reputation: 21263
I am writing C code but have to do a lot of calls to qsort which is taking most of the time. I notice that C++'s sort is faster than qsort. Is it possible for me to use it somehow? Here is a MWE in C:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
int main(void) {
int sz;
srand(time(NULL));
printf("Enter the size of array::");
scanf("%d",&sz);
uint32_t *arr = malloc(sz * sizeof *arr);
int i;
for(i=0;i<sz;i++)
arr[i]=rand();
clock_t begin = clock();
qsort(arr, sz, sizeof *arr, cmpfunc);
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%f seconds\n", time_spent);
printf("%d\n", arr[10]);
return 0;
}
Upvotes: 0
Views: 127
Reputation: 29985
Yes, it is possible. C++ is designed to handle such things without much hassle. You need to compile the C++ function separately and then link it to your project:
The header should be valid C and C++. You need to use extern "C"
by checking if it's C++:
// i32sort.h
#pragma once
#include <stdint.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C"
#endif // __cplusplus
void i32sort(int32_t*, size_t);
The source file is straight C++:
// i32sort.cpp
#include "i32sort.h"
#include <algorithm>
extern "C" void i32sort(int32_t* const data, size_t const size)
{
std::sort(data, data + size);
}
Then compile it without linking:
$ clang++ -c i32sort.cpp -O3 -Wall -Wextra
Then include the i32sort.h
header in your source file as usual:
// main.c
#include <stdio.h>
#include "i32sort.h"
int main(void)
{
int32_t arr[] = { 5, 4, 3, 2, 1 };
size_t const sz = sizeof (arr) / sizeof (* arr);
i32sort(arr, sz);
for (size_t i = 0; i < sz; ++i)
printf("%d ", (int) arr[i]);
putchar('\n');
}
While compiling your program, link it with the object file you generated previously:
$ clang main.c i32sort.o -O3 -Wall -Wextra
$ ./a
1 2 3 4 5
Upvotes: 5