介绍

V语言在HN上经常被讨论,号称有几个优点:

  1. 安全(默认不可变变量等类似Rust特性)
  2. 简单易用(语法一看就懂)
  3. 内置包管理工具(VPM)
  4. 跨平台UI

目的

  1. 初步了解V语言;
  2. 学习valgrind工具获取程序运行信息;
  3. 冒泡排序Rust对比V语言;
  4. 作为技术决策的调研数据;

V的其它优势

可以将C语言工程直接翻译为V

image.png

hot reload

类似于增量编译,每次修改代码不需要编译整个工程

基于OpenGL/Metel/DirectX11的图形库

  1. 加载3D模型和材质
  2. Camera
  3. 骨骼动画

交叉编译容易

加一个参数就可以在Windows平台上编译为Linux,这个比较强大,目前主流交叉编译的项目例如ReactNative,Electron的做法都比这个要麻烦。
v -os windows 或者 v -os linux 即可。
没搞懂它背后如何实现的,可能搞了一种字节码和runtime。

测试条件

硬件

CPU: Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz 3.19 GHz

RAM: 16.0 GB

OS

Microsoft Windows 11
WSL2 Ubuntu 22.04.2 LTS

项目

  1. 文件读取
  2. JSON parse
  3. 冒泡排序

所以正好有兴趣测试一下V语言是否像它宣称的那么好。测试条件我选择从文件中读取JSON数据,分析后对数组进行冒泡排序,这个测试第一可以测试IO性能,第二增加了JSON parse的过程,最后用冒泡排序查看内存使用情况。

代码如下:

import os
import time
import json

fn main() {
    sw := time.new_stopwatch()
    str := os.read_file('../data.json')!
    mut arr := json.decode([][]f64, str)!
    // println(arr)
    for i in 0..arr.len {
        bubble_sort(mut arr[i])
        // println(arr[i])
    }
    println('消耗时间 : ${sw.elapsed().milliseconds()}ms')
}


// Bubble Sort
[direct_array_access]
fn bubble_sort(mut array []f64) {
    for i in 0..array.len {
        for j in 0..array.len - 1 - i {
            if array[j] > array[j + 1] {
                array[j], array[j + 1] = array[j + 1], array[j]
            }
        }
    }
    // println('${array[i]}')
}

Rust部分代码

use std::fs;
use std::io::{Write, BufReader, BufRead, Error};
#[macro_use]
extern crate serde_json;

fn bubble_sort<T: PartialOrd>(arr: &mut [T]) {
    for i in 0..arr.len() {
        for j in 0..arr.len() - 1 - i {
            // println!("{}", arr[j]);
            if arr[j] > arr[j + 1] {
                arr.swap(j, j + 1);
            }
        }
    }
}

fn main() -> Result<(), Error> {
    let path = "../data.json";
    println!("In file {}", path);
    let contents = fs::read_to_string(path)
        .expect("Should have been able to read the file");
    let v: Vec<Vec<f64>> = serde_json::from_str(&contents).unwrap();
    // println!("{:?}",v);
    for mut x in v {
        bubble_sort(&mut x);
    }
    Ok(())
}

执行命令

Memory:
valgrind --tool=memcheck ./target/release/rust
valgrind --tool=memcheck ./sort

CPU:
valgrind --tool=callgrind ./target/release/rust
valgrind --tool=callgrind ./sort
# CPU结果生成图
gprof2dot --format=callgrind --output=out.dot ./callgrind.out.521
dot -Tpng out.dot -o graph.png

测试结果

V

==507==
==507== HEAP SUMMARY:
==507==     in use at exit: 2,992 bytes in 11 blocks
==507==   total heap usage: 505,129 allocs, 505,118 frees, 32,341,222 bytes allocated
==507==
==507== LEAK SUMMARY:
==507==    definitely lost: 0 bytes in 0 blocks
==507==    indirectly lost: 0 bytes in 0 blocks
==507==      possibly lost: 2,992 bytes in 11 blocks
==507==    still reachable: 0 bytes in 0 blocks
==507==         suppressed: 0 bytes in 0 blocks
==507== Rerun with --leak-check=full to see details of leaked memory
==507==
==507== Use --track-origins=yes to see where uninitialised values come from
==507== For lists of detected and suppressed errors, rerun with: -s
==507== ERROR SUMMARY: 1990 errors from 102 contexts (suppressed: 0 from 0)

Rust

==504== Memcheck, a memory error detector
==504== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==504== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==504== Command: ./target/release/rust
==504==
In file ../data.json
==504==
==504== HEAP SUMMARY:
==504==     in use at exit: 0 bytes in 0 blocks
==504==   total heap usage: 1,159 allocs, 1,159 frees, 21,370,367 bytes allocated
==504==
==504== All heap blocks were freed -- no leaks are possible
==504==
==504== For lists of detected and suppressed errors, rerun with: -s
==504== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

精简版

内存

Rust:1159次alloc,1159次free,共20.38MB

V: 505129次alloc, 505118次free,共30.84MB

CPU

V

sort.png

Rust

graph.png

结果

  1. V语言内存占用显然比Rust多。
  2. JSON parse后,V使用了11.65%的CPU时间用于__memcpy_avx_unaligned_erm,内存对齐?没搞懂,反正V的时间比Rust长很多。

所有代码在:
tcper/rustvsv (github.com)


知心哥哥
447 声望16 粉丝

前端工程专家