C# 和python性能比较(排序算法为例)
1,环境
C#: .net core6.0
python: python3.7
2,任务
排序长度为200的整数列
3, C#代码及时间
// sort.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Learn3
{
public class Solution
{
public static List<int> Solve1(List<int> l)
{
List<int> li = new();
li.Add(l[0]);
for(int i=1; i<l.Count;i++)
{
Insert_List(l[i], li);
}
return li;
}
public static int Find_index(int a, List<int> l) // 寻找索引, 前提是l 有序.
{
if (l[0] >= a) { return 0; }
int x = -1, y = l.Count();
int z;
while ((y-x)>1)
{
z = (int)(x + y) / 2;
if( a > l[z]) { x = z; }
else if ( a < l[z]) { y = z; }
else
{
return z;
}
}
return (int)(x+y)/2 + 1;
}
public static List<int> Random_List(int n, int m=100)
{
Random r = new();
List<int> l = new();
while(n !=0)
{
l.Add(r.Next(0, m));
n -= 1;
}
return l;
}
public static void Insert_List(int n, List<int> l)
{
l.Insert(Solution.Find_index(n, l), n);
}
}
}
// program.cs
using System.Diagnostics;
namespace Learn3
{
public class Program
{
public static void Main(string[] args)
{
Stopwatch s = new();
var l = Solution.Random_List(200, 500);
l.ForEach(Console.WriteLine);
Console.WriteLine();
Console.WriteLine();
s.Start();
Solution.Solve1(l).ForEach(Console.WriteLine);
// l.Sort();
// l.ForEach(Console.WriteLine);
// 大家可以试一下直接用l.sort()的时间,其实差不多.
s.Stop();
Console.WriteLine($"time: {s.Elapsed.Milliseconds} ms");
}
}
}
平均大概237毫秒
python代码及时间
import random
import time
def index(n:int, l:list):
a = -1; b = len(l);
while (b-a)>1:
c = int((a+b)/2);
if (l[c] > n):
b = c
elif (l[c]<n):
a = c
else:
return c
return int((a+b)/2)+1
def solve(l:list):
li = [-1, ];
i = 0;
while (i<len(l)):
#print(index(l[i], li))
li.insert(index(l[i], li), l[i])
i+=1
li.remove(-1)
return li
def randomlist(n, m):
l= [];
for i in range(0,n):
l.append(random.randint(0, m))
return l;
l = randomlist(200, 500)
print(l)
t = time.time()
print(solve(l))
print(f"time:{time.time() - t}")
时间情况:
平均 535毫秒.