I wanted to create a formal comparison between C and Julia performance. For this purpose I wanted to compare different sorting algorithms, starting with the bubble. In Julia I wrote it like:
using BenchmarkTools
function bubble_sort(v::AbstractArray{T}) where T<:Real
for _ in 1:length(v)-1
for i in 1:length(v)-1
if v[i] > v[i+1]
v[i], v[i+1] = v[i+1], v[i]
end
end
end
return v
end
v = rand(Int32, 100_000)
@timed bubble_sort(_v)
In the case of C code (I don't know to program in C so I apologize for the code):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static void swap(int *xp, int *yp){
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bubble_sort(int arr[], int n){
int i, j;
for (j = 0; j < n - 1; j++){
for (i = 0; i < n - 1; i++){
if (arr[i] > arr[i+1]){
swap(&arr[i], &arr[i+1]);
}
}
}
}
int main(){
int arr_sz = 100000;
int arr[arr_sz], i;
for (i = 0; i < arr_sz; i++){
arr[i] = rand();
}
double cpu_time_used;
clock_t begin = clock();
bubble_sort(arr, arr_sz);
clock_t end = clock();
cpu_time_used = ((double) (end - begin)) / CLOCKS_PER_SEC;
printf("time %f\n", cpu_time_used);
return 0;
}
The performance difference is (in my computer):
| Julia | C |
|---|---|
| 20s | ~50s |
I suppose that I have a big mistake in the C code, but I am not able to find it out, or is just Julia faster in loops?
Update: performance optimization
- Changed the type to int32 in Julia so it is the same as C
swapmethod as static (+1s improvement on average)- compiling optimization (detailed bellow)
Instead of gcc main.c, I've used different optimization flags, as also the clang compiler. Results:
| Time (s) | |
|---|---|
| Julia | 19.13 |
gcc -O main.c |
47.58 |
gcc -O1 main.c |
15.98 |
gcc -O2 main.c |
19.52 |
gcc -O3 main.c |
19.20 |
gcc -Os main.c |
17.72 |
clang -O0 main.c |
51.59 |
clang -O1 main.c |
16.78 |
clang -O2 main.c |
13.53 |
clang -O3 main.c |
13.57 |
clang -Ofast main.c |
12.39 |
clang -Os main.c |
18.85 |
clang -Oz main.c |
15.64 |
clang -Og main.c |
16.37 |