Skip to content

Instantly share code, notes, and snippets.

@andrewrk
Created February 9, 2019 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewrk/b9734f9c310d8b79ec7271e7c0df4023 to your computer and use it in GitHub Desktop.
Save andrewrk/b9734f9c310d8b79ec7271e7c0df4023 to your computer and use it in GitHub Desktop.
testing performance of safety-checked vector addition
const std = @import("std");
const Timer = std.os.time.Timer;
const IntType = i32;
const vector_size = 4;
const total_vectors = 100000000;
const total_integers = total_vectors * vector_size;
test "bench" {
const bytes = @sizeOf(IntType) * total_integers;
const scalar_bps = blk: {
var timer = try Timer.start();
const start = timer.lap();
add_a_lot_of_scalars();
const end = timer.read();
const elapsed_s = @intToFloat(f64, end - start) / std.os.time.ns_per_s;
break :blk bytes / elapsed_s;
};
const vector_bps = blk: {
var timer = try Timer.start();
const start = timer.lap();
add_a_lot_of_vectors();
const end = timer.read();
const elapsed_s = @intToFloat(f64, end - start) / std.os.time.ns_per_s;
break :blk bytes / elapsed_s;
};
std.debug.warn("\n");
std.debug.warn("scalar = {Bi}/s\n", @floatToInt(usize, scalar_bps));
std.debug.warn("vector = {Bi}/s\n", @floatToInt(usize, vector_bps));
}
fn add_a_lot_of_scalars() void {
var a: IntType = 1234;
var b: IntType = 5678;
var i: usize = 0;
while (i < total_integers) : (i += 1) {
var result = a + b;
}
}
fn add_a_lot_of_vectors() void {
var a: @Vector(vector_size, IntType) = [1]IntType{1234} ** vector_size;
var b: @Vector(vector_size, IntType) = [1]IntType{5678} ** vector_size;
var i: usize = 0;
while (i < total_vectors) : (i += 1) {
var result = a + b;
}
}
$ ./zig test test.zig
Test 1/1 bench...
scalar = 893.2965688705444MiB/s
vector = 3.581999500282109GiB/s
OK
All tests passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment