I have a code in hand that I want to optimize further if it's possible.
I have searched and could not found any further methods to optimize it.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace EditorPlayer
{
internal static class Program
{
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public unsafe static void UnsafeQuickSort(int[] data)
{
fixed(int* pData = data)
{
UnsafeQuickSortRecursive(pData, 0, data.Length - 1);
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)]
private unsafe static void UnsafeQuickSortRecursive(int* data, int left, int right)
{
int i = left - 1;
int j = right;
while (true)
{
int d = data[left];
do i++; while (data[i] < d);
do j--; while (data[j] > d);
if (i < j)
{
int tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
else
{
if (left < j) UnsafeQuickSortRecursive(data, left, j);
if (++j < right) UnsafeQuickSortRecursive(data, j, right);
return;
}
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
internal static void Main(string[] args)
{
int[] array = new int[10000000];
Random rnd = new Random();
for (int i = 0; i < array.Length; i++)
{
array[i] = rnd.Next(100000);
}
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
UnsafeQuickSort(array);
stopwatch.Stop();
Console.WriteLine($"Time took: {stopwatch.Elapsed.TotalMilliseconds}");
stopwatch.Restart();
Console.ReadLine();
}
}
}
The code above has also a identical twin written in c++ but c++ gives much better results. I would usually expect the difference would be around %5-%20 but it's way more than that. It's nearly %240.
In my machine C++ takes 230 ms while C# takes 550. I am looking for further tips to reduce the C# execution time.
Can you give any headsup ?
Note: This is tested on .NET 7