diff --git a/build.zig b/build.zig index 9bf202b..5e774a2 100644 --- a/build.zig +++ b/build.zig @@ -15,8 +15,7 @@ pub fn build(b: *std.Build) void { // set a preferred release mode, allowing the user to decide how to optimize. const optimize = b.standardOptimizeOption(.{}); - const module = b.addModule("hamt", .{ .source_file = .{ .path = "src/lib.zig" } }); - _ = module; + const hamt_module = b.addModule("hamt", .{ .source_file = .{ .path = "src/lib.zig" } }); const lib = b.addStaticLibrary(.{ .name = "hamt", @@ -32,6 +31,19 @@ pub fn build(b: *std.Build) void { // running `zig build`). b.installArtifact(lib); + // Benchmark + const bench = b.addExecutable(.{ + .name = "hamt-benchmark", + .root_source_file = .{ .path = "src/bench.zig" }, + .target = target, + .optimize = optimize, + }); + bench.addModule("hamt", hamt_module); + + const bench_cmd = b.addRunArtifact(bench); + const bench_step = b.step("bench", "Run benchmark"); + bench_step.dependOn(&bench_cmd.step); + // Creates a step for unit testing. This only builds the test executable // but does not run it. const main_tests = b.addTest(.{ diff --git a/src/bench.zig b/src/bench.zig new file mode 100644 index 0000000..6b68fdf --- /dev/null +++ b/src/bench.zig @@ -0,0 +1,41 @@ +const std = @import("std"); +const HashArrayMappedTrie = @import("hamt").HashArrayMappedTrie; + +const StringContext = struct { + pub const Digest = u64; + + pub fn hash(input: []const u8) Digest { + return std.hash.Wyhash.hash(0, input); + } + + pub fn eql(left: []const u8, right: []const u8) bool { + return std.mem.eql(u8, left, right); + } +}; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer std.debug.assert(!gpa.deinit()); + + const allocator = gpa.allocator(); + + const keys = try allocator.alloc([32]u8, 10); + defer allocator.free(keys); + + var rand = std.rand.DefaultPrng.init(0); + for (keys) |*key| rand.fill(key); + + var trie = HashArrayMappedTrie([]const u8, void, StringContext).init(); + defer trie.deinit(allocator); + + for (keys) |*key| { + try trie.insert(allocator, key, {}); + } + + var timer = try std.time.Timer.start(); + for (keys) |*key| { + _ = trie.search(key); + } + + std.debug.print("{}ns\n", .{timer.read()}); +}