net8正式版出来两个月,现在性能到底如何呢,做个简单的例子和其他语言比较一下,测试内容是查找1000000以内的质数,代码不多,但包含了循环计算和Math库函数调用,直观的看一下语言之间差距是多少,心里有个底,测试机是笔记本surface book 2 intel i7 有个四五年了,不过还能跑
首先来看看google的王牌语言golang,语法简单但性能号称不输C++,先看一下go 1.20.2
package main
import (
"fmt"
"math"
"time"
)
func isPrime(num int) bool {
if num <= 1 {
return false
}
for i := 2; i <= int(math.Sqrt(float64(num))); i++ {
if num%i == 0 {
return false
}
}
return true
}
func countPrimes(n int) int {
count := 0
for i := 2; i < n; i++ {
if isPrime(i) {
count++
}
}
return count
}
func main() {
num := 1000000
startTime := time.Now()
result := countPrimes(num)
endTime := time.Now()
fmt.Printf("The number of prime numbers less than %d is: %d\n", num, result)
fmt.Printf("Execution time: %v\n", endTime.Sub(startTime))
}
编译之后看看耗时是多少
然后看看net6
using System;
using System.Diagnostics;
namespace FindPrimeNet6
{
class Program
{
static bool IsPrime(int num)
{
if (num <= 1)
{
return false;
}
for (int i = 2; i <= Math.Sqrt(num); i++)
{
if (num % i == 0)
{
return false;
}
}
return true;
}
static int CountPrimes(int n)
{
int count = 0;
for (int i = 2; i < n; i++)
{
if (IsPrime(i))
{
count++;
}
}
return count;
}
static void Main(string[] args)
{
int num = 1000000;
Stopwatch timer = Stopwatch.StartNew();
int result = CountPrimes(num);
timer.Stop();
Console.WriteLine($"The number of prime numbers less than {num} is: {result}");
Console.WriteLine($"Execution time: {timer.ElapsedMilliseconds:F4} ms");
}
}
}
运行一下看看
然后重头来了net8 开启aot怎么样呢
看来速度没提升,应该是启动速度提高了
然后我们再看看大家心目中最慢的python,装了3.11.7版本
?
#import numba
import math
import time
#@numba.jit
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
#@numba.jit
def count_primes(n):
count = 0
for i in range(2, n):
if is_prime(i):
count += 1
return count
num = 1000000
start_time = time.perf_counter()
result = count_primes(num)
end_time = time.perf_counter()
time_elapsed = end_time - start_time
print(f"The number of prime numbers less than {num} is: {result}")
print(f"Execution time: {time_elapsed*1000:.4f}ms")
看看普通模式跑跑要多少毫秒
竟然3秒7 是golang10倍,然后让我们开了jit再跑一次
看起来 并没有差前两个语言很多
然后打包exe再执行一次 差强人意哈哈 就这样吧,将就用,希望能给大家一个参考