Skip to content

Commit a08ca15

Browse files
committed
adding initial repo commit
0 parents  commit a08ca15

File tree

10 files changed

+622
-0
lines changed

10 files changed

+622
-0
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
zig-out/
2+
zig-cache/
3+
.zig-cache/

build.zig

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const std = @import("std");
2+
3+
pub fn build(b: *std.Build) void {
4+
const target = b.standardTargetOptions(.{});
5+
const optimize = b.standardOptimizeOption(.{
6+
.preferred_optimize_mode = .ReleaseFast
7+
});
8+
9+
const exe = b.addExecutable(.{
10+
.name = "bench",
11+
.root_source_file = b.path("src/main.zig"),
12+
.target = target,
13+
.optimize = optimize,
14+
});
15+
16+
exe.addCSourceFile(.{
17+
.file = b.path("src/hw_counter.c"),
18+
.flags = &.{ "-O3" }
19+
});
20+
21+
exe.linkLibC();
22+
23+
b.installArtifact(exe);
24+
25+
const run_cmd = b.addRunArtifact(exe);
26+
27+
const run_step = b.step("run", "run stats test");
28+
29+
run_step.dependOn(&run_cmd.step);
30+
}

build.zig.zon

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
.{
2+
// This is the default name used by packages depending on this one. For
3+
// example, when a user runs `zig fetch --save <url>`, this field is used
4+
// as the key in the `dependencies` table. Although the user can choose a
5+
// different name, most users will stick with this provided value.
6+
//
7+
// It is redundant to include "zig" in this name because it is already
8+
// within the Zig package namespace.
9+
.name = "Stats",
10+
11+
// This is a [Semantic Version](https://semver.org/).
12+
// In a future version of Zig it will be used for package deduplication.
13+
.version = "0.0.0",
14+
15+
// This field is optional.
16+
// This is currently advisory only; Zig does not yet do anything
17+
// with this value.
18+
//.minimum_zig_version = "0.11.0",
19+
20+
// This field is optional.
21+
// Each dependency must either provide a `url` and `hash`, or a `path`.
22+
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
23+
// Once all dependencies are fetched, `zig build` no longer requires
24+
// internet connectivity.
25+
.dependencies = .{
26+
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
27+
//.example = .{
28+
// // When updating this field to a new URL, be sure to delete the corresponding
29+
// // `hash`, otherwise you are communicating that you expect to find the old hash at
30+
// // the new URL.
31+
// .url = "https://example.com/foo.tar.gz",
32+
//
33+
// // This is computed from the file contents of the directory of files that is
34+
// // obtained after fetching `url` and applying the inclusion rules given by
35+
// // `paths`.
36+
// //
37+
// // This field is the source of truth; packages do not come from a `url`; they
38+
// // come from a `hash`. `url` is just one of many possible mirrors for how to
39+
// // obtain a package matching this `hash`.
40+
// //
41+
// // Uses the [multihash](https://multiformats.io/multihash/) format.
42+
// .hash = "...",
43+
//
44+
// // When this is provided, the package is found in a directory relative to the
45+
// // build root. In this case the package's hash is irrelevant and therefore not
46+
// // computed. This field and `url` are mutually exclusive.
47+
// .path = "foo",
48+
49+
// // When this is set to `true`, a package is declared to be lazily
50+
// // fetched. This makes the dependency only get fetched if it is
51+
// // actually used.
52+
// .lazy = false,
53+
//},
54+
},
55+
56+
// Specifies the set of files and directories that are included in this package.
57+
// Only files and directories listed here are included in the `hash` that
58+
// is computed for this package. Only files listed here will remain on disk
59+
// when using the zig package manager. As a rule of thumb, one should list
60+
// files required for compilation plus any license(s).
61+
// Paths are relative to the build root. Use the empty string (`""`) to refer to
62+
// the build root itself.
63+
// A directory listed here means that all files within, recursively, are included.
64+
.paths = .{
65+
"build.zig",
66+
"build.zig.zon",
67+
"src",
68+
// For example...
69+
//"LICENSE",
70+
//"README.md",
71+
},
72+
}

results/test.csv

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
name,clock_mean,clock_median,clock_variance,clock_stddev,clock_curtosis,clock_skew,instructions,branches,branch_misses,cache_misses
2+
indexOfScalar,156.85800,150.00000,518.64542,22.77379,2.53409,0.90341,2027.91800,356.55000,25.65300,5.69500
3+
indexOfPosLinear,4747.56000,2945.00000,13095785.38326,3618.80994,2.72652,1.49433,81907.91100,18953.29100,24.29100,3.51400

src/CODE_DUMP

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
const data = try std.heap.page_allocator.alloc(f64, 1_000);
2+
defer std.heap.page_allocator.free(data);
3+
4+
var timer = std.time.Timer.start() catch unreachable;
5+
6+
//// start by calculating our noise floor so we can adjust other
7+
//// samples to account for any overhead accrued by measuring
8+
noise_floor = calculateNoiseFloor(data);
9+
std.debug.print("noise floor: {}\n", .{ noise_floor });
10+
11+
for (data[0..]) |*sample| {
12+
13+
const needle = rand.int(u8);
14+
15+
timer.reset();
16+
17+
forceCall(foo, .{ haystack, needle });
18+
19+
// TODO: same here - subtract from overall times
20+
sample.* = @as(f64, @floatFromInt(timer.read())) - noise_floor;
21+
}
22+
23+
const foo_stats = BaseStats.init("foo", data);
24+
25+
for (data[0..]) |*sample| {
26+
27+
const needle = rand.int(u8);
28+
29+
timer.reset();
30+
31+
forceCall(bar, .{ haystack, needle });
32+
33+
// TODO: same here - subtract from overall times
34+
sample.* = @as(f64, @floatFromInt(timer.read())) - noise_floor;
35+
}
36+
37+
const bar_stats = BaseStats.init("bar", data);
38+
39+
std.debug.print("{}", .{ foo_stats });
40+
std.debug.print("{}", .{ bar_stats });

src/hw_counter.c

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
2+
#include <asm/unistd.h>
3+
#include <linux/perf_event.h>
4+
#include <stdio.h>
5+
#include <stdlib.h>
6+
#include <string.h>
7+
#include <sys/ioctl.h>
8+
#include <unistd.h>
9+
10+
#include <inttypes.h>
11+
#include <sys/types.h>
12+
13+
#include "hw_counter.h"
14+
15+
static long perf_event_open(
16+
struct perf_event_attr *hw_event,
17+
pid_t pid,
18+
int cpu,
19+
int group_fd,
20+
unsigned long flags
21+
) {
22+
return syscall(__NR_perf_event_open, hw_event, pid, cpu, group_fd, flags);
23+
}
24+
25+
long counter_start(unsigned long long COUNT_TYPE)
26+
{
27+
struct perf_event_attr pe;
28+
memset(&pe, 0, sizeof(struct perf_event_attr));
29+
30+
pe.type = PERF_TYPE_HARDWARE;
31+
pe.size = sizeof(struct perf_event_attr);
32+
pe.config = COUNT_TYPE;
33+
pe.disabled = 1;
34+
pe.exclude_kernel = 1;
35+
pe.exclude_hv = 1;
36+
37+
long fd = perf_event_open(&pe, 0, -1, -1, 0);
38+
39+
if (fd == -1) {
40+
fprintf(stderr, "Error opening leader %llx\n", pe.config);
41+
exit(EXIT_FAILURE);
42+
}
43+
44+
ioctl(fd, PERF_EVENT_IOC_RESET, 0);
45+
ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);
46+
47+
return fd;
48+
}
49+
50+
long long count_read(long fd) {
51+
long long count;
52+
ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
53+
read(fd, &count, sizeof(long long));
54+
close(fd);
55+
return count;
56+
}
57+
58+
long instruction_start() {
59+
return counter_start(PERF_COUNT_HW_INSTRUCTIONS);
60+
}
61+
long branch_start() {
62+
return counter_start(PERF_COUNT_HW_BRANCH_INSTRUCTIONS);
63+
}
64+
long branch_miss_start() {
65+
return counter_start(PERF_COUNT_HW_BRANCH_MISSES);
66+
}
67+
long cache_miss_start() {
68+
return counter_start(PERF_COUNT_HW_CACHE_MISSES);
69+
}
70+
71+
Descriptors all_start() {
72+
Descriptors desc;
73+
desc.fds[0] = instruction_start();
74+
desc.fds[1] = branch_start();
75+
desc.fds[2] = branch_miss_start();
76+
desc.fds[3] = cache_miss_start();
77+
return desc;
78+
}
79+
80+
Counts all_read(Descriptors desc) {
81+
Counts counts;
82+
counts.data[0] = count_read(desc.fds[0]);
83+
counts.data[1] = count_read(desc.fds[1]);
84+
counts.data[2] = count_read(desc.fds[2]);
85+
counts.data[3] = count_read(desc.fds[3]);
86+
return counts;
87+
}

src/hw_counter.h

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
typedef struct {
2+
long fds[4];
3+
} Descriptors;
4+
5+
typedef struct {
6+
long long data[4];
7+
} Counts;
8+
9+
// These functions return a file-descriptor that
10+
// can be passed to the count_read function
11+
long instruction_start();
12+
long branch_start();
13+
long branch_miss_start();
14+
long cache_miss_start();
15+
16+
// expects a file descriptor that was created by
17+
// one of the "foo_start" functions above
18+
long long count_read(long);
19+
20+
// open each metric and return an array of descriptors
21+
Descriptors all_start();
22+
23+
// read from descriptors returned by all_start
24+
Counts all_read(Descriptors);
25+

src/main.zig

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
const std = @import("std");
2+
3+
const stats = @import("stats.zig");
4+
5+
pub fn main() !void {
6+
7+
///////////////////////////////////////////////
8+
9+
var prng = std.Random.DefaultPrng.init(42);
10+
const rand = prng.random();
11+
12+
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
13+
const allocator = gpa.allocator();
14+
15+
// default timer - call reset before each measurement
16+
var timer = std.time.Timer.start() catch @panic("Clock not found.");
17+
18+
// create csv for testing purposes
19+
var csv = try std.fs.cwd().createFile("results/test.csv", .{ });
20+
const writer = csv.writer();
21+
22+
// add the header row to the csv
23+
try writer.writeAll(stats.CSV_COLUMN_NAMES);
24+
25+
/////////////////////////////////////////////
26+
27+
var data = try stats.DataBlock.init(allocator, 1000);
28+
defer data.deinit(allocator);
29+
30+
const haystack = try allocator.alloc(u8, 100_000);
31+
defer allocator.free(haystack);
32+
33+
rand.bytes(haystack);
34+
35+
////////////////////////////////////////////
36+
37+
data.reset();
38+
39+
for (0..data.samples()) |_| {
40+
41+
const needle = rand.int(u8);
42+
43+
const desc = stats.hw.all_start();
44+
45+
timer.reset();
46+
47+
stats.forceCall(foo, .{ haystack, needle });
48+
49+
data.append(timer.read(), desc);
50+
}
51+
52+
const foo_stats = data.stats("indexOfScalar");
53+
54+
////////////////////////////////////////////
55+
56+
data.reset();
57+
58+
for (0..data.samples()) |_| {
59+
60+
const needle = rand.int(u8);
61+
62+
const desc = stats.hw.all_start();
63+
64+
timer.reset();
65+
66+
stats.forceCall(bar, .{ haystack, needle });
67+
68+
data.append(timer.read(), desc);
69+
}
70+
71+
const bar_stats = data.stats("indexOfPosLinear");
72+
73+
////////////////////////////////////////////
74+
75+
// append stats as a new row in the csv
76+
try foo_stats.write(writer);
77+
try bar_stats.write(writer);
78+
79+
std.debug.print("{}", .{ foo_stats });
80+
std.debug.print("{}", .{ bar_stats });
81+
82+
////////////////////////////////////////////
83+
}
84+
85+
// helpers to normalize the interface - not necessary
86+
pub fn foo(haystack: []const u8, needle: u8) ?usize {
87+
return std.mem.indexOfScalar(u8, haystack, needle);
88+
}
89+
90+
pub fn bar(haystack: []const u8, needle: u8) ?usize {
91+
return std.mem.indexOfPosLinear(u8, haystack, 0, &.{ needle });
92+
}
93+

src/root.zig

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const std = @import("std");
2+
const testing = std.testing;
3+
4+
export fn add(a: i32, b: i32) i32 {
5+
return a + b;
6+
}
7+
8+
test "basic add functionality" {
9+
try testing.expect(add(3, 7) == 10);
10+
}

0 commit comments

Comments
 (0)