MoonBit:真的有那么快?

前言

MoonBit是一个国产编程语言,号称高性能。
本文将对其进行测试。

编译器版本

MoonBit:0.1.20250312
Rust编译器:rustc-1.85.0
C编译器:MinGW gcc-14.2.0

工具准备

1.命令运行时间统计–timer.py

DeepSeek-v3写的一段程序,用于统计命令运行的时间。

import subprocess
import time

def run_command_and_measure_time():
    print("命令运行时间统计程序")
    print("输入 'exit' 或 'quit' 退出程序")
    
    while True:
        # 获取用户输入
        command = input("\n请输入要执行的命令: ").strip()
        
        # 检查退出条件
        if command.lower() in ['exit', 'quit']:
            print("程序退出。")
            break
            
        if not command:
            print("请输入有效的命令。")
            continue
            
        try:
            # 记录开始时间
            start_time = time.time()
            
            # 执行命令
            print(f"\n执行命令: {command}")
            print("----------------------------------------")
            
            # 使用subprocess运行命令
            process = subprocess.Popen(
                command,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                universal_newlines=True
            )
            
            # 获取输出和错误
            stdout, stderr = process.communicate()
            
            # 记录结束时间
            end_time = time.time()
            elapsed_time = end_time - start_time
            
            # 打印输出
            if stdout:
                print(stdout)
            if stderr:
                print(stderr)
                
            print("----------------------------------------")
            print(f"命令执行完成,耗时: {elapsed_time:.4f} 秒")
            
        except Exception as e:
            print(f"执行命令时出错: {e}")

if __name__ == "__main__":
    run_command_and_measure_time()
    

2.命令开始输出时间统计

MoonBit不能直接单文件编译,只能moon run moon.mbt --target native运行,所以用这个记录运行时间。

import subprocess
import time

def measure_command_output_latency(command):
    """
    测量命令从开始执行到开始输出的时间
    
    参数:
        command (str/list): 要执行的命令(字符串或列表形式)
    
    返回:
        float: 从开始执行到首次输出的时间(秒)
        str: 命令的首行输出
    """
    # 记录开始时间
    start_time = time.time()
    
    # 启动子进程
    process = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=True if isinstance(command, str) else False,
        universal_newlines=True
    )
    
    # 读取首行输出
    first_output = None
    while True:
        # 检查是否有输出
        line = process.stdout.readline()
        if line:
            first_output = line.strip()
            break
        
        # 检查进程是否已结束但无输出
        if process.poll() is not None:
            break
        
        # 短暂休眠避免CPU占用过高
        time.sleep(0.001)
    
    # 计算耗时
    elapsed_time = time.time() - start_time
    
    # 清理进程
    process.terminate()
    try:
        process.wait(timeout=1)
    except subprocess.TimeoutExpired:
        process.kill()
    
    return elapsed_time, first_output

if __name__ == "__main__":
    # 示例用法
    command = input("请输入要测量的命令: ")
    
    try:
        latency, output = measure_command_output_latency(command)
        print(f"\n命令从开始执行到首次输出的时间: {latency:.3f}秒")
        if output:
            print(f"首行输出: {output}")
        else:
            print("命令没有产生输出")
    except Exception as e:
        print(f"执行命令时出错: {e}")

编译速度

test1.输出数字100000次

编译器 时间测试1 时间测试2 时间测试3
gcc 0.3281s 0.3124s 0.3125s
go build 0.8793s 0.5799s 0.6063s
rustc 0.5129s 0.5468s 0.5154s
moon 0.234s 0.420s 0.237s

运行速度

test1.输出数字1000000次

注:由于临时出的问题,以下数据是手动测量的。

语言 时间测试1 时间测试2 时间测试3
C 2.9s 4.1s 3s
Go 5.6s 4.2s 4.0s
Rust 5.8s 5.0s 5.8s
MoonBit 2.5s 2.2s 2.2s

test2.斐波那契数列(46)

C
#include
int fb(double u){
    if(u==1)	return 1;
    else if(u==0)	return 0;
    else	return fb(u-1)+fb(u-2);
}
int main(){
        printf("%d\n",fb(46));
}

Golang
package main

import "fmt"

func fb(u int) uint64 {
    switch u {
    case 0:
        return 0
    case 1:
        return 1
    default:
        return fb(u-1) + fb(u-2)
    }
}

func main() {
    fmt.Println(fb(46))
}

Rust
fn fb(u: i64) -> i64 {
    match u {
        0 => 0,
        1 => 1,
        _ => fb(u - 1) + fb(u - 2),
    }
}

fn main() {
    println!("{}", fb(46));
}

MoonBit
fn fib(u:Int64) -> Int64{
  match(u){
    0 => return 0;
    1 => return 1;
    _ => return fib(u-1)+fib(u-2);
  }
}
fn main{
    println(fib(46).to_string())
}

C:16.366800s
Go:10.329359s
Rust:20.292208s
MoonBit:11.238415s
虽然MoonBit没有最快,但是也只比第一慢了1秒左右,可能还是moon run moon.mbt命令导致的误差。

总结

MoonBit编译和运行速度都还是挺快的,我相信MoonBit未来的潜力。

你可能感兴趣的:(小实验系列,windows,c语言,python,rust,go,开发语言)