diff options
author | iurii plugatarov <[email protected]> | 2024-07-28 21:07:00 +0200 |
---|---|---|
committer | iurii plugatarov <[email protected]> | 2024-07-28 21:07:00 +0200 |
commit | a679ae0a00adc299ab89efb69fad44ebab777d35 (patch) | |
tree | 243d4ce9ea0effe6fcf89e61cee80b10b562925d /src/benchmark.zig | |
download | dsazitty-a679ae0a00adc299ab89efb69fad44ebab777d35.tar.gz |
init
Diffstat (limited to 'src/benchmark.zig')
-rw-r--r-- | src/benchmark.zig | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/src/benchmark.zig b/src/benchmark.zig new file mode 100644 index 0000000..4c30609 --- /dev/null +++ b/src/benchmark.zig @@ -0,0 +1,55 @@ +const std = @import("std"); +const Random = std.Random; +const time = std.time; +const bubble = @import("sort/bubble.zig"); +const selection = @import("sort/selection.zig"); +const insertion = @import("sort/insertion.zig"); +const testing = std.testing; + +fn benchmark(comptime T: type, comptime sort_fn: fn (type, []T) void, n: usize, runs: usize) !u64 { + var prng = std.rand.DefaultPrng.init(0); + var random = prng.random(); + var total_time: u64 = 0; + for (0..runs) |_| { + const list = try testing.allocator.alloc(T, n); + defer testing.allocator.free(list); + for (list) |*item| { + item.* = random.int(T); + } + const start = time.milliTimestamp(); + sort_fn(T, list); + const end = time.milliTimestamp(); + total_time += @intCast(end - start); + } + return total_time / runs; +} + +test "bubble sort benchmark" { + const runs = 10; + const sizes = [_]usize{ 100, 1000, 10000 }; + std.debug.print("\nBubble Sort Benchmark:\n", .{}); + for (sizes) |size| { + const avg_time = try benchmark(i64, bubble.sort, size, runs); + std.debug.print("Average time for N={d}: {d} ms\n", .{ size, avg_time }); + } +} + +test "selection sort benchmark" { + const runs = 10; + const sizes = [_]usize{ 100, 1000, 10000 }; + std.debug.print("\nSelection Sort Benchmark:\n", .{}); + for (sizes) |size| { + const avg_time = try benchmark(i64, selection.sort, size, runs); + std.debug.print("Average time for N={d}: {d} ms\n", .{ size, avg_time }); + } +} + +test "insertion sort benchmark" { + const runs = 10; + const sizes = [_]usize{ 100, 1000, 10000 }; + std.debug.print("\nInsertion Sort Benchmark:\n", .{}); + for (sizes) |size| { + const avg_time = try benchmark(i64, insertion.sort, size, runs); + std.debug.print("Average time for N={d}: {d} ms\n", .{ size, avg_time }); + } +} |