在这篇文章中,我对异步和多线程编程在Rust、Go、Java、C#、Python、Node.js和Elixir等流行语言中的内存消耗进行了比较。
不久前,我需要比较一些处理大量网络连接的计算机程序的性能。我发现这些程序的内存消耗差异巨大,甚至超过了20倍。有些程序仅消耗100 MB左右的内存,而其他一些在处理1万个连接时却达到了接近3 GB的内存消耗。不幸的是,这些程序非常复杂,而且在功能上也有所不同,因此很难直接进行比较并得出有意义的结论,因为这不是一个公平的比较。这促使我想到创建一个合成基准测试。
让我们启动N个并发任务,每个任务等待10秒钟,然后在所有任务完成后程序退出。任务的数量由命令行参数控制。
let mut handles = Vec::new();for _ in 0..num_threads {let handle = thread::spawn(|| {thread::sleep(Duration::from_secs(10));});handles.push(handle);}for handle in handles {handle.join().unwrap();}
let mut tasks = Vec::new();for _ in 0..num_tasks {tasks.push(task::spawn(async {time::sleep(Duration::from_secs(10)).await;}));}for task in tasks {task.await.unwrap();}
var wg sync.WaitGroupfor i := 0; i < numRoutines; i++ {wg.Add(1)go func() {defer wg.Done()time.Sleep(10 * time.Second)}()}wg.Wait()
List<Thread> threads = new ArrayList<>();for (int i = 0; i < numTasks; i++) {Thread thread = new Thread(() -> {try {Thread.sleep(Duration.ofSeconds(10));} catch (InterruptedException e) {}});thread.start();threads.add(thread);}for (Thread thread : threads) {thread.join();}
List<Thread> threads = new ArrayList<>();for (int i = 0; i < numTasks; i++) {Thread thread = Thread.startVirtualThread(() -> {try {Thread.sleep(Duration.ofSeconds(10));} catch (InterruptedException e) {}});threads.add(thread);}for (Thread thread : threads) {thread.join();}
List<Task> tasks = new List<Task>();for (int i = 0; i < numTasks; i++){Task task = Task.Run(async () =>{await Task.Delay(TimeSpan.FromSeconds(10));});tasks.Add(task);}await Task.WhenAll(tasks);
const delay = util.promisify(setTimeout);const tasks = [];for (let i = 0; i < numTasks; i++) {tasks.push(delay(10000);}await Promise.all(tasks);
async def perform_task():await asyncio.sleep(10)tasks = []for task_id in range(num_tasks):task = asyncio.create_task(perform_task())tasks.append(task)await asyncio.gather(*tasks)
tasks =for _ <- 1..num_tasks doTask.async(fn ->:timer.sleep(10000)end)endTask.await_many(tasks, :infinity)
硬件:Intel(R) Xeon(R) CPU E3-1505M v6 @ 3.00GHz 操作系统:Ubuntu 22.04 LTS, Linux p5520 5.15.0-72-generic Rust版本:1.69 Go版本:1.18.1 Java版本:OpenJDK "21-ea" build 21-ea+22-1890 .NET版本:6.0.116 Node.js版本:v12.22.9 Python版本:3.10.6 Elixir版本:Erlang/OTP 24 erts-12.2.1, Elixir 1.12.2

我们可以看到,程序明显分为两组。



文章转载自云原生数据库,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




