Add rust and Go benchmarks for encoding json.
This commit is contained in:
3
src/lib.rs
Normal file
3
src/lib.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
#![feature(test)]
|
||||
mod vec3;
|
||||
extern crate test;
|
||||
40
src/vec3.rs
Normal file
40
src/vec3.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Default, Debug, Serialize, PartialEq, Copy, Clone)]
|
||||
pub struct Vec3 {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use test::Bencher;
|
||||
|
||||
#[test]
|
||||
fn test_vec3_to_json() {
|
||||
let vecs = vec![Vec3 {
|
||||
x: 1.0,
|
||||
y: 2.0,
|
||||
z: 3.0,
|
||||
}];
|
||||
assert_eq!(
|
||||
serde_json::to_string(&vecs).expect("failed to json encode"),
|
||||
r#"[{"x":1.0,"y":2.0,"z":3.0}]"#
|
||||
);
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_vec3_to_json(b: &mut Bencher) {
|
||||
let vecs: Vec<Vec3> = (0..1000)
|
||||
.map(|i| Vec3 {
|
||||
x: 255. * i as f32 / 1000.,
|
||||
y: 255. * i as f32 / 1000.,
|
||||
z: 255. * i as f32 / 1000.,
|
||||
})
|
||||
.collect();
|
||||
|
||||
b.iter(|| serde_json::to_string(&vecs));
|
||||
}
|
||||
}
|
||||
43
src/vec3_test.go
Normal file
43
src/vec3_test.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type Vec3 struct {
|
||||
X float32 `json:"x"`
|
||||
Y float32 `json:"y"`
|
||||
Z float32 `json:"z"`
|
||||
}
|
||||
|
||||
func TestVec3ToJSON(t *testing.T) {
|
||||
vecs := []Vec3{{X: 1.0, Y: 2.0, Z: 3.0}}
|
||||
|
||||
got, err := json.Marshal(vecs)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal: %v", err)
|
||||
}
|
||||
want := []byte(`[{"x":1,"y":2,"z":3}]`)
|
||||
if !reflect.DeepEqual(want, got) {
|
||||
t.Fatalf("got != want\nGot: %s\nWant: %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkVec3ToJSON(b *testing.B) {
|
||||
var vecs []Vec3
|
||||
|
||||
for i := 0; i < 1000; i++ {
|
||||
vecs = append(vecs, Vec3{
|
||||
X: 255. * float32(i) / 1000.,
|
||||
Y: 255. * float32(i) / 1000.,
|
||||
Z: 255. * float32(i) / 1000.,
|
||||
})
|
||||
}
|
||||
for i := 0; i < b.N; i++ {
|
||||
if _, err := json.Marshal(vecs); err != nil {
|
||||
b.Fatalf("Failed to marshal: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user