我想对 C 和 Julia 的性能进行正式比较。为此,我想比较不同的排序算法,从气泡开始。在 Julia 中我这样写:
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)
Run Code Online (Sandbox Code Playgroud)
对于 C 代码(我不知道用 C 编程,所以我对代码表示歉意):
#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 …Run Code Online (Sandbox Code Playgroud)