16 Commits
7 changed files with 722 additions and 899 deletions
+178 -213
View File
@@ -1,268 +1,233 @@
# zig_units # dimal — Dimensional Analysis for Zig
`zig_units` lets you attach physical units to numeric values so that dimension mismatches (like adding distance to time) become **compile errors** rather than silent bugs. A comptime-first dimensional analysis module for Zig. If you try to add meters to seconds, **it won't compile**. That's the point.
At runtime, a `Quantity` is just its underlying numeric value — **zero memory overhead.** Born from a space simulation where `i128` positions were needed to avoid float imprecision far from the origin, this module grew into a full physical-unit type system with zero runtime overhead.
```zig > **Source:** [git.bouvais.lu/adrien/zig-dimal](https://git.bouvais.lu/adrien/zig-dimal)
const velocity = distance.divBy(time); // Result type: L¹T⁻¹ ✓ > **Minimum Zig version:** `0.16.0`
const error = mass.add(velocity); // COMPILE ERROR: M¹ != L¹T⁻¹
```
**Requirements:** Zig `0.16.0` ---
## Features
- **100% comptime** — all dimension and unit tracking happens at compile time. No added memory, *almost* native performance.
- **Compile-time dimension errors** — adding `Meter` to `Second` is a compile error, not a runtime panic.
- **Automatic unit conversion** — use `.to()` to convert between compatible units (e.g. `km/h` → `m/s`). Scale factors are resolved at comptime.
- **Full SI prefix support** — `pico`, `nano`, `micro`, `milli`, `centi`, `deci`, `kilo`, `mega`, `giga`, `tera`, `peta`, and more.
- **Time scale support** — `min`, `hour`, `year` built in.
- **Scalar and Vector types** — operate on individual values or fixed-size arrays with the same dimensional safety.
- **Built-in physical quantities** — `dma.Base` provides ready-made types for `Velocity`, `Acceleration`, `Force`, `Energy`, `Pressure`, `ElectricCharge`, `ThermalConductivity`, and many more.
- **Rich formatting** — values print with their unit automatically: `9.81m.s⁻²`, `42m.kg.s⁻¹`, `0.172km`.
- **`i128` support** — the whole reason this exists. Use large integers for high-precision fixed-point positions without manual conversion.
- **Tests and benchmarks included** — run them and see how it performs on your machine (results welcome!).
---
## The 7 SI Base Dimensions
| Symbol | Dimension | SI Unit |
|--------|----------------------|----------|
| `L` | Length | `m` |
| `M` | Mass | `g` |
| `T` | Time | `s` |
| `I` | Electric Current | `A` |
| `Tp` | Temperature | `K` |
| `N` | Amount of Substance | `mol` |
| `J` | Luminous Intensity | `cd` |
--- ---
## Installation ## Installation
### 1. Add as a Zig dependency ### 1. Fetch the dependency
```bash
zig fetch --save https://github.com/YOUR_USERNAME/zig_units/archive/refs/heads/main.tar.gz ```sh
zig fetch --save git+https://git.bouvais.lu/adrien/zig-dimal#b9647e04266e3f395cfd26b41622b0c119a1e5be
``` ```
### 2. Configure `build.zig` This will add the following to your `build.zig.zon` automatically:
```zig ```zig
const zig_units = b.dependency("zig_units", .{ .dependencies = .{
.target = target, .dimal = .{
.optimize = optimize, .url = "git+https://git.bouvais.lu/adrien/zig-dimal#b9647e04266e3f395cfd26b41622b0c119a1e5be",
}); .hash = "dimal-0.1.0-WNhSHvomAQAX1ISvq9ZBal-Gam6078y8hE67aC82l63V",
// Add to your module or executable },
exe.root_module.addImport("units", zig_units.module("zig_units")); },
``` ```
--- ### 2. Wire it up in `build.zig`
## Quick Start: Using Predefined Quantities
`units.Base` provides a clean way to instantiate common physical types without manually defining dimensions.
```zig ```zig
const std = @import("std"); const std = @import("std");
const units = @import("units");
pub fn main() !void { pub fn build(b: *std.Build) void {
// Instantiate types for f32 backing const target = b.standardTargetOptions(.{});
const Meter = units.Base.Meter.Of(f32); const dimal = b.dependency("dimal", .{}).module("dimal");
const Second = units.Base.Second.Of(f32);
const dist = Meter{ .value = 10.0 };
const time = Second{ .value = 2.0 };
// Arithmetic is type-safe and creates the correct resulting dimension const exe = b.addExecutable(.{
const vel = dist.divBy(time); // Type is Velocity (L/T) .name = "my_project",
.root_module = b.createModule(.{
std.debug.print("Speed: {f}\n", .{vel}); // Output: 5m.s⁻¹ .root_source_file = b.path("src/main.zig"),
.target = target,
.imports = &.{.{
.name = "dimal",
.module = dimal,
}},
}),
});
b.installArtifact(exe);
} }
``` ```
--- ### 3. Import in your code
### Core Arithmetic Operations
Dimensional analysis is handled entirely at compile-time. If the math doesn't make physical sense, it won't compile.
```zig ```zig
const M = units.Base.Meter.Of(f32); const dma = @import("dimal");
const S = units.Base.Second.Of(f32); const Scalar = dma.Scalar;
const Dimensions = dma.Dimensions;
const dist = M{ .value = 100.0 }; const Scales = dma.Scales;
const time = S{ .value = 5.0 };
// 1. Addition & Subtraction (Must have same dimensions)
const two_dist = dist.add(dist); // 200.0m
const zero = dist.sub(dist); // 0.0m
// 2. Division (Subtracts dimension exponents)
// Result: Velocity (L¹ T⁻¹)
const vel = dist.divBy(time); // 20.0 m.s⁻¹
// 3. Multiplication (Adds dimension exponents)
// Result: Area (L²)
const area = dist.mulBy(dist); // 100.0 m²
// 4. Chained Operations
// Result: Acceleration (L¹ T⁻²)
const accel = dist.divBy(time).divBy(time); // 4.0 m.s⁻²
``` ```
--- ---
## Defining Custom Quantities ## Quick Start
You aren't limited to the built-in library. You can define any physical quantity by specifying its **Dimensions** ### Defining unit types
(powers of base units) and its **Scale** (SI prefixes).
### 1. Create a custom dimension A `Scalar` type is parameterized by three things: the numeric type (`f64`, `i128`, …), the dimensions (which physical quantities, and their exponents), and the scales (SI prefixes or custom time units).
Dimensions are defined by 7 base SI units: `L` (Length), `M` (Mass), `T` (Time), `I` (Current), `Tp` (Temp), `N` (Substance), `J` (Intensity).
```zig ```zig
const Dims = units.Dimensions; const Meter = Scalar(f64, .init(.{ .L = 1 }), .init(.{}));
const Scales = units.Scales; const NanoMeter = Scalar(i64, .init(.{ .L = 1 }), .init(.{ .L = .n }));
const KiloMeter = Scalar(f64, .init(.{ .L = 1 }), .init(.{ .L = .k }));
// Frequency is T⁻¹ const Second = Scalar(f64, .init(.{ .T = 1 }), .init(.{}));
const FreqDims = Dims.init(.{ .T = -1 }); const Velocity = Scalar(f64, .init(.{ .L = 1, .T = -1 }), .init(.{}));
const Kmh = Scalar(f64, .init(.{ .L = 1, .T = -1 }), .init(.{ .L = .k, .T = .hour }));
// Force is M¹ L¹ T⁻²
const ForceDims = Dims.init(.{ .M = 1, .L = 1, .T = -2 });
``` ```
### 2. Create a custom Type Or use the pre-built helpers from `dma.Base`:
Combine a numeric type, the dimensions, and a scale.
```zig ```zig
const Hertz = units.Quantity(f32, FreqDims, Scales.init(.{})); const Acceleration = dma.Base.Acceleration.Of(f64);
const KmhSpeed = dma.Base.Speed.Scaled(f64, Scales.init(.{ .L = .k, .T = .hour }));
// A specialized scale: Millimeters per Second Squared
const MmPerSecSq = units.Quantity(f32,
Dims.init(.{ .L = 1, .T = -2 }),
Scales.init(.{ .L = .m }) // .m = milli
);
``` ```
### Kinematics example
```zig
const v0 = Velocity{ .value = 10.0 }; // 10 m/s
const accel = Acceleration{ .value = 9.81 }; // 9.81 m/s²
const time = Second{ .value = 5.0 }; // 5 s
// d = v₀t + ½at²
const d1 = v0.mulBy(time); // → Meter
const d2 = accel.mulBy(time.mulBy(time)).scale(0.5); // → Meter
const dist = d1.add(d2);
const v_final = v0.add(accel.mulBy(time));
std.debug.print("Distance: {d} | {d}\n", .{ dist, dist.to(KiloMeter) });
// Distance: 172.625m | 0.172625km
std.debug.print("Final speed: {d:.2}\n", .{v_final});
// Final speed: 59.05m.s⁻¹
```
### Unit conversion
`.to()` converts between compatible units at comptime. Mixing incompatible dimensions is a **compile error**.
```zig
const speed_kmh = Kmh{ .value = 120.0 };
const speed_ms = speed_kmh.to(Velocity); // 33.333... m/s — comptime ratio
// This would NOT compile:
// const bad = speed_kmh.to(Second); // "Dimension mismatch in to: L1T-1 vs T1"
```
### Working with Vectors
Every `Scalar` type exposes a `.Vec3` and a generic `.Vec(n)`:
```zig
const Vec3Meter = Meter.Vec3; // or: Vector(3, Meter)
const pos = Vec3Meter{ .data = .{ 100, 200, 300 } };
const t = Second{ .value = 10 };
const vel = pos.divByScalar(t); // → Vec3 of Velocity (m/s)
std.debug.print("{d}\n", .{vel}); // (10, 20, 30)m.s⁻¹
```
Vectors support: `add`, `sub`, `mulBy`, `divBy`, `mulByScalar`, `divByScalar`, `negate`, `to`, `length`, `lengthSqr`.
--- ---
## Unit Conversions ## API Reference
The library handles SI prefixes (`k`, `m`, `u`, `n`, etc.) and time aliases (`.min`, `.hour`) automatically. ### `Scalar(T, dims, scales)`
When performing arithmetic between different scales, the **finer (smaller) scale wins** to preserve precision.
```zig | Method | Description |
const KM = units.Base.Meter.Scaled(f32, Scales.init(.{ .L = .k })); // Kilometers |---|---|
const M = units.Base.Meter.Of(f32); // Meters | `.add(rhs)` | Add two quantities of the same dimension. Auto-converts scales. |
| `.sub(rhs)` | Subtract. Auto-converts scales. |
| `.mulBy(rhs)` | Multiply — dimensions are **summed**. `m * s⁻¹` → `m·s⁻¹`. |
| `.divBy(rhs)` | Divide — dimensions are **subtracted**. `m / s` → `m·s⁻¹`. |
| `.to(DestType)` | Convert to another unit of the same dimension. Compile error on mismatch. |
| `.vec3()` | Wrap the value in a `Vec3` of the same type. |
| `.Vec(n)` | Get the `Vector(n, Self)` type. |
const d1 = KM{ .value = 1.2 }; // 1.2 km ### `dma.Base` — Pre-built quantities
const d2 = M{ .value = 300.0 }; // 300 m
const total = d1.add(d2); // Result is 1500.0 (Meters) A selection of what's available (call `.Of(T)` for base units, `.Scaled(T, scales)` for custom scales):
const final = total.to(KM); // Explicitly convert back to KM -> 1.5
``` `Meter`, `Second`, `Gramm`, `Kelvin`, `ElectricCurrent`, `Speed`, `Acceleration`, `Inertia`, `Force`, `Pressure`, `Energy`, `Power`, `Area`, `Volume`, `Density`, `Frequency`, `Viscosity`, `ElectricCharge`, `ElectricPotential`, `ElectricResistance`, `MagneticFlux`, `ThermalCapacity`, `ThermalConductivity`, and more.
### `Scales` — SI prefixes
| Tag | Factor |
|---|---|
| `.P` | 10¹⁵ |
| `.T` | 10¹² |
| `.G` | 10⁹ |
| `.M` | 10⁶ |
| `.k` | 10³ |
| `.none` | 1 |
| `.c` | 10⁻² |
| `.m` | 10⁻³ |
| `.u` | 10⁻⁶ |
| `.n` | 10⁻⁹ |
| `.p` | 10⁻¹² |
| `.f` | 10⁻¹⁵ |
| `.min` | 60 |
| `.hour` | 3600 |
| `.year` | 31 536 000 |
--- ---
## Physical Vectors (Vec3) ## Running Tests and Benchmarks
Physical quantities often come in 3D vectors (Position, Velocity, Force). Every `Quantity` type has a `.Vec3` alias built-in. ```sh
```zig
const Vec3M = units.Base.Meter.Of(f32).Vec3;
const gravity = Vec3M{ .data = .{ 0, -9.81, 0 } };
const pos = Vec3M.initDefault(0); // [0, 0, 0]
// Vectors support standard operations
const length = gravity.length(); // Returns f32: 9.81
const double = gravity.scale(2.0);
```
You can also create a Vector of any length.
Vec3 found in a Quantity is just a convenience.
```zig
const M = units.Base.Meter.Of(f32);
const Vec10M = units.QuantityVec(10, Meter);
const gravity = Vec10M.initDefault(1);
const length = gravity.length(); // Returns f32: 1.0
```
---
## High Precision & Integer Backing
While most libraries default to `f32` or `f64`, `zig_units` is mainly designed to support **large-bit integers (`i128`, `i256`)**.
This is critical for applications like **space simulations**, where floating-point numbers suffer from "jitter" or "flickering"
once you travel far from the origin. By using an `i128` with a millimeter scale, you can represent the diameter
of the observable universe with millimeter precision—something impossible with `f64`.
### Avoiding Floating-Point Jitter
```zig
// Millimeter precision using 128-bit integers
const MM = units.Base.Meter.Scaled(i128, units.Scales.init(.{ .L = .m }));
const KM = units.Base.Meter.Scaled(i128, units.Scales.init(.{ .L = .k }));
const solar_system_dist = KM{ .value = 150_000_000 }; // 150 million km
const ship_nudge = MM{ .value = 5 }; // 5 mm
// The library performs exact integer math for conversions.
// Resulting type is MM (the finer scale), maintaining perfect precision.
const new_pos = solar_system_dist.add(ship_nudge);
```
### Integer-Specific Features
* **Exact Conversions:** When converting between integer scales (e.g., `km` to `m`), the library uses fast-path native multiplication.
* **Safe Vector Lengths:** `QuantityVec.length()` includes a custom integer square root implementation, allowing you to calculate distances between coordinates without ever casting to a float.
* **Zero Drift:** Unlike floats, repeated additions and subtractions of integers never accumulate "epsilon" drift, ensuring your simulation remains deterministic.
* **Precision-First Scaling:** When operating on two different scales (e.g., adding `km` and `mm`), the result automatically adopts the finer scale (`mm`). This ensures **zero implicit data loss** during calculation. You only lose precision if you *explicitly* choose to convert back to a coarser scale using `.to()`.
---
## SI Scales Reference
| Prefix | Enum | Factor |
| :--- | :--- | :--- |
| **Kilo** | `.k` | 10³ |
| **Mega** | `.M` | 10⁶ |
| **Giga** | `.G` | 10⁹ |
| **Milli** | `.m` | 10⁻³ |
| **Micro** | `.u` | 10⁻⁶ |
| **Minute**| `.min` | 60 |
| **Hour** | `.hour`| 3,600 |
---
## API Summary
### `Quantity(T, dims, scales)`
- `.add(rhs)` / `.sub(rhs)`: Automatic scaling, requires same dimensions.
- `.mulBy(rhs)` / `.divBy(rhs)`: Composes dimensions (e.g., $L \times L = L^2$).
- `.scale(scalar)`: Multiply by a raw number (preserves dimensions).
- `.to(OtherType)`: Safely convert between scales of the same dimension.
- `.vec3()`: Create a 3D vector from a scalar.
### `Dimensions`
- `L`: Length (m)
- `M`: Mass (g)
- `T`: Time (s)
- `I`: Current (A)
- `Tp`: Temperature (K)
- `N`: Amount (mol)
- `J`: Intensity (cd)
---
## Testing & Benchmarks
`zig_units` comes with a comprehensive test suite that verifies dimensional correctness, SI prefix scaling,
and vector math accuracy across all numeric types.
### Running Tests
To run the full suite of unit tests and performance benchmarks:
```bash
zig build test zig build test
zig build benchmark
``` ```
### Benchmarks Benchmark results are very welcome — feel free to share yours!
When you run the tests, the library also executes a performance benchmark.
This measures the cost of operations (in nanoseconds per operation) across different backing types (`i32` to `f128`) and vector lengths.
Because all dimensional logic is resolved at **compile-time**, you will see that `Quantity` operations perform at the same speed as raw primitive math. ---
**Example Benchmark Output:** ## Roadmap / Known Limitations
```text
Quantity<T> benchmark — 100,000 iterations, 10 samples/cell
┌───────────────────┬──────┬─────────────────────┬─────────────────────┐ - More operations beyond `add`, `sub`, `mulBy`, `divBy` (e.g. `pow`, `sqrt`).
│ Operation │ Type │ ns / op (± delta) │ Throughput (ops/s) │ - SIMD acceleration for `Vector` operations.
├───────────────────┼──────┼─────────────────────┼─────────────────────┤ - Some paths may still fall back to runtime computation — optimization ongoing.
│ add │ i32 │ 0.18 ns ±0.02 │ 5555555556 │ - More test coverage.
│ mulBy │ f64 │ 0.22 ns ±0.01 │ 4545454545 │
└───────────────────┴──────┴─────────────────────┴─────────────────────┘
```
### Verification Examples ---
The test suite ensures that:
- **Dimension Safety:** Chained operations like `dist.divBy(time).divBy(time)` correctly result in an Acceleration type. ## License
- **Scale Accuracy:** Adding `1km + 1mm` results exactly in `1000001mm` without truncation.
- **Formatting:** Quantities print correctly with Unicode superscripts (e.g., `9.81m.s⁻²`). See the repository for license details.
- **Vector Math:** Euclidean lengths for both floats and integers are verified against known constants.
+25 -27
View File
@@ -2,40 +2,38 @@ const std = @import("std");
pub fn build(b: *std.Build) void { pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{}); const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{ .preferred_optimize_mode = .ReleaseSmall }); const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "Zig_Units", // 1. Define the module so other projects can import it
_ = b.addModule("dimal", .{
.root_source_file = b.path("src/main.zig"),
});
const exe_tests = b.addTest(.{
.root_module = b.createModule(.{ .root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"), .root_source_file = b.path("src/main.zig"),
.target = target, .target = target,
.optimize = optimize, .optimize = optimize,
}),
.test_runner = .{ .path = b.path("test_runner.zig"), .mode = .simple },
});
const run_exe_tests = b.addRunArtifact(exe_tests);
const test_step = b.step("test", "Run tests");
test_step.dependOn(&run_exe_tests.step);
const bench_exe = b.addExecutable(.{
.name = "benchmark",
.root_module = b.createModule(.{
.root_source_file = b.path("src/benchmark.zig"),
.target = target,
.imports = &.{}, .imports = &.{},
}), }),
}); });
b.installArtifact(exe); b.installArtifact(bench_exe);
const run_step = b.step("run", "Run the app");
const run_cmd = b.addRunArtifact(exe); const run_bench = b.addRunArtifact(bench_exe);
run_step.dependOn(&run_cmd.step); const bench_step = b.step("benchmark", "Run the benchmark suite");
bench_step.dependOn(&run_bench.step);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const exe_tests = b.addTest(.{
.root_module = exe.root_module,
.test_runner = .{
.path = .{ .cwd_relative = "test_runner.zig" },
.mode = .simple,
},
});
// A run step that will run the second test executable.
const run_exe_tests = b.addRunArtifact(exe_tests);
const test_step = b.step("test", "Run tests");
test_step.dependOn(&run_exe_tests.step);
} }
+5 -73
View File
@@ -1,81 +1,13 @@
.{ .{
// This is the default name used by packages depending on this one. For .name = .dimal,
// example, when a user runs `zig fetch --save <url>`, this field is used .version = "0.1.0",
// as the key in the `dependencies` table. Although the user can choose a .fingerprint = 0x9453b1ff1e52d858,
// different name, most users will stick with this provided value.
//
// It is redundant to include "zig" in this name because it is already
// within the Zig package namespace.
.name = .Zig_Units,
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",
// Together with name, this represents a globally unique package
// identifier. This field is generated by the Zig toolchain when the
// package is first created, and then *never changes*. This allows
// unambiguous detection of one package being an updated version of
// another.
//
// When forking a Zig project, this id should be regenerated (delete the
// field and run `zig build`) if the upstream project is still maintained.
// Otherwise, the fork is *hostile*, attempting to take control over the
// original project's identity. Thus it is recommended to leave the comment
// on the following line intact, so that it shows up in code reviews that
// modify the field.
.fingerprint = 0x934b00cf88f69b22, // Changing this has security and trust implications.
// Tracks the earliest Zig version that the package considers to be a
// supported use case.
.minimum_zig_version = "0.16.0", .minimum_zig_version = "0.16.0",
// This field is optional. .dependencies = .{},
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
//.example = .{
// // When updating this field to a new URL, be sure to delete the corresponding
// // `hash`, otherwise you are communicating that you expect to find the old hash at
// // the new URL. If the contents of a URL change this will result in a hash mismatch
// // which will prevent zig from using it.
// .url = "https://example.com/foo.tar.gz",
//
// // This is computed from the file contents of the directory of files that is
// // obtained after fetching `url` and applying the inclusion rules given by
// // `paths`.
// //
// // This field is the source of truth; packages do not come from a `url`; they
// // come from a `hash`. `url` is just one of many possible mirrors for how to
// // obtain a package matching this `hash`.
// //
// // Uses the [multihash](https://multiformats.io/multihash/) format.
// .hash = "...",
//
// // When this is provided, the package is found in a directory relative to the
// // build root. In this case the package's hash is irrelevant and therefore not
// // computed. This field and `url` are mutually exclusive.
// .path = "foo",
//
// // When this is set to `true`, a package is declared to be lazily
// // fetched. This makes the dependency only get fetched if it is
// // actually used.
// .lazy = false,
//},
},
// Specifies the set of files and directories that are included in this package.
// Only files and directories listed here are included in the `hash` that
// is computed for this package. Only files listed here will remain on disk
// when using the zig package manager. As a rule of thumb, one should list
// files required for compilation plus any license(s).
// Paths are relative to the build root. Use the empty string (`""`) to refer to
// the build root itself.
// A directory listed here means that all files within, recursively, are included.
.paths = .{ .paths = .{
"build.zig", "build.zig",
"build.zig.zon", "build.zig.zon",
"src", "src",
// For example... "test_runner.zig",
//"LICENSE",
//"README.md",
}, },
} }
+2
View File
@@ -25,6 +25,8 @@ pub fn BaseScalar(comptime d: anytype) type {
}; };
} }
pub const Dimless = BaseScalar(.{});
// ========================================== // ==========================================
// Base Quantities // Base Quantities
// ========================================== // ==========================================
+30 -424
View File
@@ -8,7 +8,7 @@ const Dimensions = @import("Dimensions.zig");
const Dimension = Dimensions.Dimension; const Dimension = Dimensions.Dimension;
pub fn Scalar(comptime T: type, comptime d: Dimensions, comptime s: Scales) type { pub fn Scalar(comptime T: type, comptime d: Dimensions, comptime s: Scales) type {
@setEvalBranchQuota(100_000); @setEvalBranchQuota(10_000_000);
return struct { return struct {
value: T, value: T,
@@ -86,10 +86,6 @@ pub fn Scalar(comptime T: type, comptime d: Dimensions, comptime s: Scales) type
} }
} }
pub inline fn scale(self: Self, sc: T) Self {
return .{ .value = self.value * sc };
}
pub inline fn to(self: Self, comptime Dest: type) Dest { pub inline fn to(self: Self, comptime Dest: type) Dest {
if (comptime !dims.eql(Dest.dims)) if (comptime !dims.eql(Dest.dims))
@compileError("Dimension mismatch in to: " ++ dims.str() ++ " vs " ++ Dest.dims.str()); @compileError("Dimension mismatch in to: " ++ dims.str() ++ " vs " ++ Dest.dims.str());
@@ -140,11 +136,21 @@ pub fn Scalar(comptime T: type, comptime d: Dimensions, comptime s: Scales) type
return Vec3.initDefault(self.value); return Vec3.initDefault(self.value);
} }
pub fn format( pub fn formatNumber(
self: Self, self: Self,
writer: *std.Io.Writer, writer: *std.Io.Writer,
options: std.fmt.Number,
) !void { ) !void {
try writer.print("{d}", .{self.value}); switch (@typeInfo(T)) {
.float, .comptime_float => try writer.printFloat(self.value, options),
.int, .comptime_int => try writer.printInt(self.value, 10, .lower, .{
.width = options.width,
.alignment = options.alignment,
.fill = options.fill,
.precision = options.precision,
}),
else => unreachable,
}
var first = true; var first = true;
inline for (std.enums.values(Dimension)) |bu| { inline for (std.enums.values(Dimension)) |bu| {
const v = dims.get(bu); const v = dims.get(bu);
@@ -187,48 +193,39 @@ test "Add" {
const added = distance.add(distance2); const added = distance.add(distance2);
try std.testing.expectEqual(30, added.value); try std.testing.expectEqual(30, added.value);
try std.testing.expectEqual(1, @TypeOf(added).dims.get(.L)); try std.testing.expectEqual(1, @TypeOf(added).dims.get(.L));
std.debug.print("KiloMeter {f} + {f} = {f} OK\n", .{ distance, distance2, added });
const KiloMeter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k })); const KiloMeter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const distance3 = KiloMeter{ .value = 2 }; const distance3 = KiloMeter{ .value = 2 };
const added2 = distance.add(distance3); const added2 = distance.add(distance3);
try std.testing.expectEqual(2010, added2.value); try std.testing.expectEqual(2010, added2.value);
try std.testing.expectEqual(1, @TypeOf(added2).dims.get(.L)); try std.testing.expectEqual(1, @TypeOf(added2).dims.get(.L));
std.debug.print("KiloMeter {f} + {f} = {f} OK\n", .{ distance, distance3, added2 });
const added3 = distance3.add(distance).to(KiloMeter); const added3 = distance3.add(distance).to(KiloMeter);
try std.testing.expectEqual(2, added3.value); try std.testing.expectEqual(2, added3.value);
try std.testing.expectEqual(1, @TypeOf(added3).dims.get(.L)); try std.testing.expectEqual(1, @TypeOf(added3).dims.get(.L));
std.debug.print("KiloMeter {f} + {f} = {f} OK\n", .{ distance3, distance, added3 });
const KiloMeter_f = Scalar(f64, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k })); const KiloMeter_f = Scalar(f64, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const distance4 = KiloMeter_f{ .value = 2 }; const distance4 = KiloMeter_f{ .value = 2 };
const added4 = distance4.add(distance).to(KiloMeter_f); const added4 = distance4.add(distance).to(KiloMeter_f);
try std.testing.expectApproxEqAbs(2.01, added4.value, 0.000001); try std.testing.expectApproxEqAbs(2.01, added4.value, 0.000001);
try std.testing.expectEqual(1, @TypeOf(added4).dims.get(.L)); try std.testing.expectEqual(1, @TypeOf(added4).dims.get(.L));
std.debug.print("KiloMeter_f {f} + {f} = {f} OK\n", .{ distance4, distance, added4 });
} }
test "Sub" { test "Sub" {
const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{})); const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const KiloMeter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const KiloMeter_f = Scalar(f64, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k })); const KiloMeter_f = Scalar(f64, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const a = Meter{ .value = 500 }; const a = Meter{ .value = 500 };
const b = Meter{ .value = 200 }; const b = Meter{ .value = 200 };
const diff = a.sub(b); const diff = a.sub(b);
try std.testing.expectEqual(300, diff.value); try std.testing.expectEqual(300, diff.value);
std.debug.print("Sub: {f} - {f} = {f} OK\n", .{ a, b, diff }); const diff2 = b.sub(a);
try std.testing.expectEqual(-300, diff2.value);
const km = KiloMeter{ .value = 1 };
const diff2 = a.sub(km);
std.debug.print("Sub cross-scale: {f} - {f} = {f}\n", .{ a, km, diff2 });
const km_f = KiloMeter_f{ .value = 2.5 }; const km_f = KiloMeter_f{ .value = 2.5 };
const m_f = Meter{ .value = 500 }; const m_f = Meter{ .value = 500 };
const diff3 = km_f.sub(m_f); const diff3 = km_f.sub(m_f);
try std.testing.expectApproxEqAbs(2000, diff3.value, 1e-4); try std.testing.expectApproxEqAbs(2000, diff3.value, 1e-4);
std.debug.print("Sub float cross-scale: {f} - {f} = {f} OK\n", .{ km_f, m_f, diff3 });
} }
test "MulBy" { test "MulBy" {
@@ -242,14 +239,12 @@ test "MulBy" {
try std.testing.expectEqual(12, area_time.value); try std.testing.expectEqual(12, area_time.value);
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.L)); try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.L));
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.T)); try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.T));
std.debug.print("MulBy: {f} * {f} = {f} OK\n", .{ d, t, area_time });
const d2 = Meter{ .value = 5.0 }; const d2 = Meter{ .value = 5.0 };
const area = d.mulBy(d2); const area = d.mulBy(d2);
try std.testing.expectEqual(15, area.value); try std.testing.expectEqual(15, area.value);
try std.testing.expectEqual(2, @TypeOf(area).dims.get(.L)); try std.testing.expectEqual(2, @TypeOf(area).dims.get(.L));
try std.testing.expectEqual(0, @TypeOf(area).dims.get(.T)); try std.testing.expectEqual(0, @TypeOf(area).dims.get(.T));
std.debug.print("MulBy: {f} * {f} = {f} OK\n", .{ d, d2, area });
} }
test "MulBy with scale" { test "MulBy with scale" {
@@ -261,7 +256,6 @@ test "MulBy with scale" {
const prod = dist.mulBy(mass); const prod = dist.mulBy(mass);
try std.testing.expectEqual(1, @TypeOf(prod).dims.get(.L)); try std.testing.expectEqual(1, @TypeOf(prod).dims.get(.L));
try std.testing.expectEqual(1, @TypeOf(prod).dims.get(.M)); try std.testing.expectEqual(1, @TypeOf(prod).dims.get(.M));
std.debug.print("MulBy scaled: {f} * {f} = {f} OK\n", .{ dist, mass, prod });
} }
test "MulBy with type change" { test "MulBy with type change" {
@@ -279,7 +273,6 @@ test "MulBy with type change" {
try std.testing.expectApproxEqAbs(12, area_time_f.value, 0.0001); try std.testing.expectApproxEqAbs(12, area_time_f.value, 0.0001);
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.L)); try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.L));
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.T)); try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.T));
std.debug.print("MulBy: {f} * {f} = {f} OK\n", .{ d, t, area_time });
} }
test "MulBy small" { test "MulBy small" {
@@ -293,23 +286,16 @@ test "MulBy small" {
try std.testing.expectEqual(12, area_time.value); try std.testing.expectEqual(12, area_time.value);
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.L)); try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.L));
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.T)); try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.T));
std.debug.print("MulBy: {f} * {f} = {f} OK\n", .{ d, t, area_time });
} }
test "Scale" { test "MulBy dimensionless" {
const DimLess = Scalar(i128, Dimensions.init(.{}), Scales.init(.{}));
const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{})); const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Second = Scalar(f32, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const d = Meter{ .value = 7 }; const d = Meter{ .value = 7 };
const scaled = d.scale(3); const scaled = d.mulBy(DimLess{ .value = 3 });
try std.testing.expectEqual(21, scaled.value); try std.testing.expectEqual(21, scaled.value);
try std.testing.expectEqual(1, @TypeOf(scaled).dims.get(.L)); try std.testing.expectEqual(1, @TypeOf(scaled).dims.get(.L));
std.debug.print("Scale int: {f} * 3 = {f} OK\n", .{ d, scaled });
const t = Second{ .value = 1.5 };
const scaled_f = t.scale(4.0);
try std.testing.expectApproxEqAbs(@as(f32, 6.0), scaled_f.value, 1e-4);
std.debug.print("Scale float: {f} * 4 = {f} OK\n", .{ t, scaled_f });
} }
test "Chained: velocity and acceleration" { test "Chained: velocity and acceleration" {
@@ -328,8 +314,6 @@ test "Chained: velocity and acceleration" {
try std.testing.expectEqual(5, accel.value); try std.testing.expectEqual(5, accel.value);
try std.testing.expectEqual(1, @TypeOf(accel).dims.get(.L)); try std.testing.expectEqual(1, @TypeOf(accel).dims.get(.L));
try std.testing.expectEqual(-2, @TypeOf(accel).dims.get(.T)); try std.testing.expectEqual(-2, @TypeOf(accel).dims.get(.T));
std.debug.print("Velocity: {f}, Acceleration: {f} OK\n", .{ velocity, accel });
} }
test "DivBy integer exact" { test "DivBy integer exact" {
@@ -343,7 +327,6 @@ test "DivBy integer exact" {
try std.testing.expectEqual(30, vel.value); try std.testing.expectEqual(30, vel.value);
try std.testing.expectEqual(1, @TypeOf(vel).dims.get(.L)); try std.testing.expectEqual(1, @TypeOf(vel).dims.get(.L));
try std.testing.expectEqual(-1, @TypeOf(vel).dims.get(.T)); try std.testing.expectEqual(-1, @TypeOf(vel).dims.get(.T));
std.debug.print("DivBy int: {f} / {f} = {f} OK\n", .{ dist, time, vel });
} }
test "Conversion chain: km -> m -> cm" { test "Conversion chain: km -> m -> cm" {
@@ -357,7 +340,6 @@ test "Conversion chain: km -> m -> cm" {
try std.testing.expectEqual(15_000, m.value); try std.testing.expectEqual(15_000, m.value);
try std.testing.expectEqual(1_500_000, cm.value); try std.testing.expectEqual(1_500_000, cm.value);
std.debug.print("Chain: {f} -> {f} -> {f} OK\n", .{ km, m, cm });
} }
test "Conversion: hours -> minutes -> seconds" { test "Conversion: hours -> minutes -> seconds" {
@@ -371,7 +353,6 @@ test "Conversion: hours -> minutes -> seconds" {
try std.testing.expectEqual(60, min.value); try std.testing.expectEqual(60, min.value);
try std.testing.expectEqual(3600, sec.value); try std.testing.expectEqual(3600, sec.value);
std.debug.print("Time chain: {f} -> {f} -> {f} OK\n", .{ h, min, sec });
} }
test "Negative values" { test "Negative values" {
@@ -381,10 +362,9 @@ test "Negative values" {
const b = Meter{ .value = 20 }; const b = Meter{ .value = 20 };
const diff = a.sub(b); const diff = a.sub(b);
try std.testing.expectEqual(-15, diff.value); try std.testing.expectEqual(-15, diff.value);
std.debug.print("Negative sub: {f} - {f} = {f} OK\n", .{ a, b, diff });
} }
test "Format Quantity" { test "Format Scalar" {
const MeterPerSecondSq = Scalar( const MeterPerSecondSq = Scalar(
f32, f32,
Dimensions.init(.{ .L = 1, .T = -2 }), Dimensions.init(.{ .L = 1, .T = -2 }),
@@ -395,396 +375,22 @@ test "Format Quantity" {
Dimensions.init(.{ .M = 1, .L = 1, .T = -1 }), Dimensions.init(.{ .M = 1, .L = 1, .T = -1 }),
Scales.init(.{ .M = .k }), Scales.init(.{ .M = .k }),
); );
const Meter = Scalar(f32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const m = Meter{ .value = 1.23456 };
const accel = MeterPerSecondSq{ .value = 9.81 }; const accel = MeterPerSecondSq{ .value = 9.81 };
const momentum = KgMeterPerSecond{ .value = 42.0 }; const momentum = KgMeterPerSecond{ .value = 42.0 };
std.debug.print("Acceleration: {f}\n", .{accel}); var buf: [64]u8 = undefined;
std.debug.print("Momentum: {f}\n", .{momentum}); var res = try std.fmt.bufPrint(&buf, "{d:.2}", .{m});
} try std.testing.expectEqualStrings("1.23m", res);
test "Benchmark" { res = try std.fmt.bufPrint(&buf, "{d}", .{accel});
const Io = std.Io; try std.testing.expectEqualStrings("9.81m.ns⁻²", res);
const ITERS: usize = 100_000;
const SAMPLES: usize = 10; // Number of samples for stats
var gsink: f64 = 0; res = try std.fmt.bufPrint(&buf, "{d}", .{momentum});
const io = std.testing.io; try std.testing.expectEqualStrings("42m.kg.s⁻¹", res);
// Standard Zig 0.16 timestamp retrieval res = try std.fmt.bufPrint(&buf, "{d:_>10.1}", .{m});
const getTime = struct { try std.testing.expectEqualStrings("_______1.2m", res);
fn f(i: Io) Io.Timestamp {
return Io.Clock.awake.now(i);
}
}.f;
const fold = struct {
fn f(comptime TT: type, s: *f64, v: TT) void {
s.* += if (comptime @typeInfo(TT) == .float)
@as(f64, @floatCast(v))
else
@as(f64, @floatFromInt(v));
}
}.f;
const getVal = struct {
fn f(comptime TT: type, i: usize, comptime mask: u7) TT {
const v: u8 = @as(u8, @truncate(i & @as(usize, mask))) + 1;
return if (comptime @typeInfo(TT) == .float) @floatFromInt(v) else @intCast(v);
}
}.f;
const Stats = struct {
median: f64,
delta: f64,
ops_per_sec: f64,
};
const computeStats = struct {
fn f(samples: []f64, iters: usize) Stats {
std.mem.sort(f64, samples, {}, std.sort.asc(f64));
const mid = samples.len / 2;
const median_ns = if (samples.len % 2 == 0) (samples[mid - 1] + samples[mid]) / 2.0 else samples[mid];
const low = samples[0];
const high = samples[samples.len - 1];
const delta_ns = (high - low) / 2.0;
const ns_per_op = median_ns / @as(f64, @floatFromInt(iters));
return .{
.median = ns_per_op,
.delta = (delta_ns / @as(f64, @floatFromInt(iters))),
.ops_per_sec = 1_000_000_000.0 / ns_per_op,
};
}
}.f;
std.debug.print(
\\
\\ Quantity<T> benchmark — {d} iterations, {d} samples/cell
\\
\\┌───────────────────┬──────┬─────────────────────┬─────────────────────┐
\\│ Operation │ Type │ ns / op (± delta) │ Throughput (ops/s) │
\\├───────────────────┼──────┼─────────────────────┼─────────────────────┤
\\
, .{ ITERS, SAMPLES });
const Types = .{ i16, i32, i64, i128, i256, f32, f64, f128 };
const TNames = .{ "i16", "i32", "i64", "i128", "i256", "f32", "f64", "f128" };
const Ops = .{ "add", "sub", "mulBy", "divBy", "scale", "to" };
var results_matrix: [Ops.len][Types.len]f64 = undefined;
comptime var tidx: usize = 0;
inline for (Types, TNames) |T, tname| {
const M = Scalar(T, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const KM = Scalar(T, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const S = Scalar(T, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
inline for (Ops, 0..) |op_name, oidx| {
var samples: [SAMPLES]f64 = undefined;
for (0..SAMPLES) |s_idx| {
var sink: T = 0;
const t_start = getTime(io);
for (0..ITERS) |i| {
const r = if (comptime std.mem.eql(u8, op_name, "add"))
(M{ .value = getVal(T, i, 63) }).add(M{ .value = getVal(T, i +% 7, 63) })
else if (comptime std.mem.eql(u8, op_name, "sub"))
(M{ .value = getVal(T, i +% 10, 63) }).sub(M{ .value = getVal(T, i, 63) })
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
(M{ .value = getVal(T, i, 63) }).mulBy(M{ .value = getVal(T, i +% 1, 63) })
else if (comptime std.mem.eql(u8, op_name, "divBy"))
(M{ .value = getVal(T, i +% 10, 63) }).divBy(S{ .value = getVal(T, i, 63) })
else if (comptime std.mem.eql(u8, op_name, "scale"))
(M{ .value = getVal(T, i, 63) }).scale(getVal(T, i +% 2, 63))
else
(KM{ .value = getVal(T, i, 15) }).to(M);
if (comptime @typeInfo(T) == .float) sink += r.value else sink ^= r.value;
}
const t_end = getTime(io);
samples[s_idx] = @as(f64, @floatFromInt(t_start.durationTo(t_end).toNanoseconds()));
fold(T, &gsink, sink);
}
const stats = computeStats(&samples, ITERS);
results_matrix[oidx][tidx] = stats.median;
std.debug.print("│ {s:<17} │ {s:<4} │ {d:>8.2} ns ±{d:<6.2} │ {d:>19.0} │\n", .{ op_name, tname, stats.median, stats.delta, stats.ops_per_sec });
}
if (comptime tidx < Types.len - 1) {
std.debug.print("├───────────────────┼──────┼─────────────────────┼─────────────────────┤\n", .{});
}
tidx += 1;
}
// Median Summary Table
std.debug.print("└───────────────────┴──────┴─────────────────────┴─────────────────────┘\n\n", .{});
std.debug.print("Median Summary (ns/op):\n", .{});
std.debug.print("┌──────────────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┐\n", .{});
std.debug.print("│ Operation │ i16 │ i32 │ i64 │ i128 │ i256 │ f32 │ f64 │ f128 │\n", .{});
std.debug.print("├──────────────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┤\n", .{});
inline for (Ops, 0..) |op_name, oidx| {
std.debug.print("│ {s:<11} │", .{op_name});
var i: usize = 0;
while (i < Types.len) : (i += 1) {
std.debug.print("{d:>6.1} │", .{results_matrix[oidx][i]});
}
std.debug.print("\n", .{});
}
std.debug.print("└──────────────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┘\n", .{});
std.debug.print("\nAnti-optimisation sink: {d:.4}\n", .{gsink});
try std.testing.expect(gsink != 0);
}
test "Overhead Analysis: Quantity vs Native" {
const Io = std.Io;
const ITERS: usize = 100_000;
const SAMPLES: usize = 5;
const io = std.testing.io;
const getTime = struct {
fn f(i: Io) Io.Timestamp {
return Io.Clock.awake.now(i);
}
}.f;
const fold = struct {
fn f(comptime TT: type, s: *f64, v: TT) void {
s.* += if (comptime @typeInfo(TT) == .float)
@as(f64, @floatCast(v))
else
@as(f64, @floatFromInt(v));
}
}.f;
// Helper to safely get a value of type T from a loop index
const getValT = struct {
fn f(comptime TT: type, i: usize) TT {
const v = (i % 100) + 1;
return if (comptime @typeInfo(TT) == .float) @floatFromInt(v) else @intCast(v);
}
}.f;
const Types = .{ i32, i64, i128, f32, f64 };
const TNames = .{ "i32", "i64", "i128", "f32", "f64" };
const Ops = .{ "add", "mulBy", "divBy" };
var gsink: f64 = 0;
std.debug.print(
\\
\\ Quantity vs Native Overhead Analysis
\\
\\┌───────────┬──────┬───────────┬───────────┬───────────┐
\\│ Operation │ Type │ Native │ Quantity │ Slowdown │
\\├───────────┼──────┼───────────┼───────────┼───────────┤
\\
, .{});
inline for (Ops, 0..) |op_name, j| {
inline for (Types, 0..) |T, tidx| {
var native_total_ns: f64 = 0;
var quantity_total_ns: f64 = 0;
const M = Scalar(T, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const S = Scalar(T, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
for (0..SAMPLES) |_| {
// --- 1. Benchmark Native ---
var n_sink: T = 0;
const n_start = getTime(io);
for (0..ITERS) |i| {
const a = getValT(T, i);
const b = getValT(T, 2);
const r = if (comptime std.mem.eql(u8, op_name, "add"))
a + b
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
a * b
else if (comptime @typeInfo(T) == .int) @divTrunc(a, b) else a / b;
if (comptime @typeInfo(T) == .float) n_sink += r else n_sink ^= r;
}
const n_end = getTime(io);
native_total_ns += @as(f64, @floatFromInt(n_start.durationTo(n_end).toNanoseconds()));
fold(T, &gsink, n_sink);
// --- 2. Benchmark Quantity ---
var q_sink: T = 0;
const q_start = getTime(io);
for (0..ITERS) |i| {
const qa = M{ .value = getValT(T, i) };
const qb = if (comptime std.mem.eql(u8, op_name, "divBy")) S{ .value = getValT(T, 2) } else M{ .value = getValT(T, 2) };
const r = if (comptime std.mem.eql(u8, op_name, "add"))
qa.add(qb)
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
qa.mulBy(qb)
else
qa.divBy(qb);
if (comptime @typeInfo(T) == .float) q_sink += r.value else q_sink ^= r.value;
}
const q_end = getTime(io);
quantity_total_ns += @as(f64, @floatFromInt(q_start.durationTo(q_end).toNanoseconds()));
fold(T, &gsink, q_sink);
}
const avg_n = (native_total_ns / SAMPLES) / @as(f64, @floatFromInt(ITERS));
const avg_q = (quantity_total_ns / SAMPLES) / @as(f64, @floatFromInt(ITERS));
const slowdown = avg_q / avg_n;
std.debug.print("│ {s:<9} │ {s:<4} │ {d:>7.2}ns │ {d:>7.2}ns │ {d:>8.2}x │\n", .{
op_name, TNames[tidx], avg_n, avg_q, slowdown,
});
}
if (j != Ops.len - 1) std.debug.print("├───────────┼──────┼───────────┼───────────┼───────────┤\n", .{});
}
std.debug.print("└───────────┴──────┴───────────┴───────────┴───────────┘\n", .{});
try std.testing.expect(gsink != 0);
}
test "Cross-Type Overhead Analysis: Quantity vs Native" {
const Io = std.Io;
const ITERS: usize = 100_000;
const SAMPLES: usize = 5;
const io = std.testing.io;
const getTime = struct {
fn f(i: Io) Io.Timestamp {
return Io.Clock.awake.now(i);
}
}.f;
const fold = struct {
fn f(comptime TT: type, s: *f64, v: TT) void {
s.* += if (comptime @typeInfo(TT) == .float)
@as(f64, @floatCast(v))
else
@as(f64, @floatFromInt(v));
}
}.f;
const getValT = struct {
fn f(comptime TT: type, i: usize) TT {
// Keep values safe and non-zero to avoid division by zero or overflows during cross-casting
const v = (i % 50) + 1;
return if (comptime @typeInfo(TT) == .float) @floatFromInt(v) else @intCast(v);
}
}.f;
// Helper for the Native baseline: explicitly casting T2 to T1 before the operation
const castTo = struct {
fn f(comptime DestT: type, comptime SrcT: type, val: SrcT) DestT {
if (comptime DestT == SrcT) return val;
const src_info = @typeInfo(SrcT);
const dest_info = @typeInfo(DestT);
if (dest_info == .int and src_info == .int) return @intCast(val);
if (dest_info == .float and src_info == .int) return @floatFromInt(val);
if (dest_info == .int and src_info == .float) return @intFromFloat(val);
if (dest_info == .float and src_info == .float) return @floatCast(val);
unreachable;
}
}.f;
const Types = .{ i16, i64, i128, f32, f64 };
const TNames = .{ "i16", "i64", "i128", "f32", "f64" };
const Ops = .{ "add", "mulBy", "divBy" };
var gsink: f64 = 0;
std.debug.print(
\\
\\ Cross-Type Overhead Analysis: Quantity vs Native
\\
\\┌─────────┬──────┬──────┬───────────┬───────────┬───────────┐
\\│ Op │ T1 │ T2 │ Native │ Quantity │ Slowdown │
\\├─────────┼──────┼──────┼───────────┼───────────┼───────────┤
\\
, .{});
inline for (Ops, 0..) |op_name, j| {
inline for (Types, 0..) |T1, t1_idx| {
inline for (Types, 0..) |T2, t2_idx| {
var native_total_ns: f64 = 0;
var quantity_total_ns: f64 = 0;
const M1 = Scalar(T1, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const M2 = Scalar(T2, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const S2 = Scalar(T2, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
for (0..SAMPLES) |_| {
// --- 1. Benchmark Native (Cast T2 to T1, then math) ---
var n_sink: T1 = 0;
const n_start = getTime(io);
for (0..ITERS) |i| {
const a = getValT(T1, i);
const b_raw = getValT(T2, 2);
const b = castTo(T1, T2, b_raw);
const r = if (comptime std.mem.eql(u8, op_name, "add"))
a + b
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
a * b
else if (comptime @typeInfo(T1) == .int)
@divTrunc(a, b)
else
a / b;
if (comptime @typeInfo(T1) == .float) n_sink += r else n_sink ^= r;
}
const n_end = getTime(io);
native_total_ns += @as(f64, @floatFromInt(n_start.durationTo(n_end).toNanoseconds()));
fold(T1, &gsink, n_sink);
// --- 2. Benchmark Quantity ---
var q_sink: T1 = 0;
const q_start = getTime(io);
for (0..ITERS) |i| {
const qa = M1{ .value = getValT(T1, i) };
const qb = if (comptime std.mem.eql(u8, op_name, "divBy"))
S2{ .value = getValT(T2, 2) }
else
M2{ .value = getValT(T2, 2) };
const r = if (comptime std.mem.eql(u8, op_name, "add"))
qa.add(qb)
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
qa.mulBy(qb)
else
qa.divBy(qb);
if (comptime @typeInfo(T1) == .float) q_sink += r.value else q_sink ^= r.value;
}
const q_end = getTime(io);
quantity_total_ns += @as(f64, @floatFromInt(q_start.durationTo(q_end).toNanoseconds()));
fold(T1, &gsink, q_sink);
}
const avg_n = (native_total_ns / SAMPLES) / @as(f64, @floatFromInt(ITERS));
const avg_q = (quantity_total_ns / SAMPLES) / @as(f64, @floatFromInt(ITERS));
const slowdown = avg_q / avg_n;
std.debug.print("│ {s:<7} │ {s:<4} │ {s:<4} │ {d:>7.2}ns │ {d:>7.2}ns │ {d:>8.2}x │\n", .{
op_name, TNames[t1_idx], TNames[t2_idx], avg_n, avg_q, slowdown,
});
}
}
if (j != Ops.len - 1) {
std.debug.print("├─────────┼──────┼──────┼───────────┼───────────┼───────────┤\n", .{});
}
}
std.debug.print("└─────────┴──────┴──────┴───────────┴───────────┴───────────┘\n", .{});
try std.testing.expect(gsink != 0);
} }
+53 -162
View File
@@ -26,74 +26,74 @@ pub fn Vector(comptime len: usize, comptime Q: type) type {
pub fn initDefault(v: T) Self { pub fn initDefault(v: T) Self {
var data: [len]T = undefined; var data: [len]T = undefined;
for (&data) |*item| item.* = v; inline for (&data) |*item| item.* = v;
return .{ .data = data }; return .{ .data = data };
} }
pub fn add(self: Self, rhs: anytype) Vector(len, Scalar(T, d, s.min(@TypeOf(rhs).scales))) { pub inline fn add(self: Self, rhs: anytype) Vector(len, Scalar(T, d, s.min(@TypeOf(rhs).scales))) {
const Tr = @TypeOf(rhs); const Tr = @TypeOf(rhs);
var res: Vector(len, Scalar(T, d, s.min(Tr.scales))) = undefined; var res: Vector(len, Scalar(T, d, s.min(Tr.scales))) = undefined;
for (self.data, 0..) |v, i| { inline for (self.data, 0..) |v, i| {
const q = (Q{ .value = v }).add(Tr.ScalarType{ .value = rhs.data[i] }); const q = (Q{ .value = v }).add(Tr.ScalarType{ .value = rhs.data[i] });
res.data[i] = q.value; res.data[i] = q.value;
} }
return res; return res;
} }
pub fn sub(self: Self, rhs: anytype) Vector(len, Scalar(T, d, s.min(@TypeOf(rhs).scales))) { pub inline fn sub(self: Self, rhs: anytype) Vector(len, Scalar(T, d, s.min(@TypeOf(rhs).scales))) {
const Tr = @TypeOf(rhs); const Tr = @TypeOf(rhs);
var res: Vector(len, Scalar(T, d, s.min(Tr.scales))) = undefined; var res: Vector(len, Scalar(T, d, s.min(Tr.scales))) = undefined;
for (self.data, 0..) |v, i| { inline for (self.data, 0..) |v, i| {
const q = (Q{ .value = v }).sub(Tr.ScalarType{ .value = rhs.data[i] }); const q = (Q{ .value = v }).sub(Tr.ScalarType{ .value = rhs.data[i] });
res.data[i] = q.value; res.data[i] = q.value;
} }
return res; return res;
} }
pub fn divBy( pub inline fn divBy(
self: Self, self: Self,
rhs: anytype, rhs: anytype,
) Vector(len, Scalar(T, d.sub(@TypeOf(rhs).dims), s.min(@TypeOf(rhs).scales))) { ) Vector(len, Scalar(T, d.sub(@TypeOf(rhs).dims), s.min(@TypeOf(rhs).scales))) {
const Tr = @TypeOf(rhs); const Tr = @TypeOf(rhs);
var res: Vector(len, Scalar(T, d.sub(Tr.dims), s.min(Tr.scales))) = undefined; var res: Vector(len, Scalar(T, d.sub(Tr.dims), s.min(Tr.scales))) = undefined;
for (self.data, 0..) |v, i| { inline for (self.data, 0..) |v, i| {
const q = (Q{ .value = v }).divBy(Tr.ScalarType{ .value = rhs.data[i] }); const q = (Q{ .value = v }).divBy(Tr.ScalarType{ .value = rhs.data[i] });
res.data[i] = q.value; res.data[i] = q.value;
} }
return res; return res;
} }
pub fn mulBy( pub inline fn mulBy(
self: Self, self: Self,
rhs: anytype, rhs: anytype,
) Vector(len, Scalar(T, d.add(@TypeOf(rhs).dims), s.min(@TypeOf(rhs).scales))) { ) Vector(len, Scalar(T, d.add(@TypeOf(rhs).dims), s.min(@TypeOf(rhs).scales))) {
const Tr = @TypeOf(rhs); const Tr = @TypeOf(rhs);
var res: Vector(len, Scalar(T, d.add(Tr.dims), s.min(Tr.scales))) = undefined; var res: Vector(len, Scalar(T, d.add(Tr.dims), s.min(Tr.scales))) = undefined;
for (self.data, 0..) |v, i| { inline for (self.data, 0..) |v, i| {
const q = (Q{ .value = v }).mulBy(Tr.ScalarType{ .value = rhs.data[i] }); const q = (Q{ .value = v }).mulBy(Tr.ScalarType{ .value = rhs.data[i] });
res.data[i] = q.value; res.data[i] = q.value;
} }
return res; return res;
} }
pub fn divByScalar( pub inline fn divByScalar(
self: Self, self: Self,
scalar: anytype, scalar: anytype,
) Vector(len, Scalar(T, d.sub(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) { ) Vector(len, Scalar(T, d.sub(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) {
var res: Vector(len, Scalar(T, d.sub(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) = undefined; var res: Vector(len, Scalar(T, d.sub(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) = undefined;
for (self.data, 0..) |v, i| { inline for (self.data, 0..) |v, i| {
const q = Q{ .value = v }; const q = Q{ .value = v };
res.data[i] = q.divBy(scalar).value; res.data[i] = q.divBy(scalar).value;
} }
return res; return res;
} }
pub fn mulByScalar( pub inline fn mulByScalar(
self: Self, self: Self,
scalar: anytype, scalar: anytype,
) Vector(len, Scalar(T, d.add(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) { ) Vector(len, Scalar(T, d.add(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) {
var res: Vector(len, Scalar(T, d.add(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) = undefined; var res: Vector(len, Scalar(T, d.add(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) = undefined;
for (self.data, 0..) |v, i| { inline for (self.data, 0..) |v, i| {
const q = Q{ .value = v }; const q = Q{ .value = v };
res.data[i] = q.mulBy(scalar).value; res.data[i] = q.mulBy(scalar).value;
} }
@@ -102,37 +102,29 @@ pub fn Vector(comptime len: usize, comptime Q: type) type {
pub fn negate(self: Self) Self { pub fn negate(self: Self) Self {
var res: Self = undefined; var res: Self = undefined;
for (self.data, 0..) |v, i| { inline for (self.data, 0..) |v, i| {
res.data[i] = -v; res.data[i] = -v;
} }
return res; return res;
} }
pub fn scale(self: Self, rhs: T) Self { pub inline fn to(self: Self, comptime DestQ: type) Vector(len, DestQ) {
var res: Self = undefined;
for (self.data, 0..) |v, i| {
res.data[i] = (Q{ .value = v }).scale(rhs).value;
}
return res;
}
pub fn to(self: Self, comptime DestQ: type) Vector(len, DestQ) {
var res: Vector(len, DestQ) = undefined; var res: Vector(len, DestQ) = undefined;
for (self.data, 0..) |v, i| { inline for (self.data, 0..) |v, i| {
res.data[i] = (Q{ .value = v }).to(DestQ).value; res.data[i] = (Q{ .value = v }).to(DestQ).value;
} }
return res; return res;
} }
pub fn lengthSqr(self: Self) T { pub inline fn lengthSqr(self: Self) T {
var sum: T = 0; var sum: T = 0;
for (self.data) |v| { inline for (self.data) |v| {
sum += v * v; sum += v * v;
} }
return sum; return sum;
} }
pub fn length(self: Self) T { pub inline fn length(self: Self) T {
const len_sq = self.lengthSqr(); const len_sq = self.lengthSqr();
if (comptime @typeInfo(T) == .int) { if (comptime @typeInfo(T) == .int) {
@@ -147,21 +139,43 @@ pub fn Vector(comptime len: usize, comptime Q: type) type {
} }
} }
pub fn format(self: Self, writer: *std.Io.Writer) !void { pub fn formatNumber(
self: Self,
writer: *std.Io.Writer,
options: std.fmt.Number,
) !void {
try writer.writeAll("("); try writer.writeAll("(");
for (self.data, 0..) |v, i| { for (self.data, 0..) |v, i| {
if (i > 0) try writer.writeAll(", "); if (i > 0) try writer.writeAll(", ");
try writer.print("{d:.2}", .{v}); switch (@typeInfo(T)) {
.float, .comptime_float => try writer.printFloat(v, options),
.int, .comptime_int => try writer.printInt(v, 10, .lower, .{
.width = options.width,
.alignment = options.alignment,
.fill = options.fill,
.precision = options.precision,
}),
else => unreachable,
}
} }
try writer.writeAll(")"); try writer.writeAll(")");
var first = true; var first = true;
inline for (std.enums.values(Dimension)) |bu| { inline for (std.enums.values(Dimension)) |bu| {
const v = dims.get(bu); const v = dims.get(bu);
if (v == 0) continue; if (comptime v == 0) continue;
if (!first) try writer.writeAll("."); if (!first)
try writer.writeAll(".");
first = false; first = false;
try writer.print("{s}{s}", .{ scales.get(bu).str(), bu.unit() });
if (v != 1) try hlp.printSuperscript(writer, v); const uscale = scales.get(bu);
if (bu == .T and (uscale == .min or uscale == .hour or uscale == .year))
try writer.print("{s}", .{uscale.str()})
else
try writer.print("{s}{s}", .{ uscale.str(), bu.unit() });
if (v != 1)
try hlp.printSuperscript(writer, v);
} }
} }
}; };
@@ -182,8 +196,12 @@ test "Format VectorX" {
const accel = MeterPerSecondSq.Vec3.initDefault(9.81); const accel = MeterPerSecondSq.Vec3.initDefault(9.81);
const momentum = KgMeterPerSecond.Vec3{ .data = .{ 43, 0, 11 } }; const momentum = KgMeterPerSecond.Vec3{ .data = .{ 43, 0, 11 } };
std.debug.print("Acceleration: {f}\n", .{accel}); var buf: [64]u8 = undefined;
std.debug.print("Momentum: {f}\n", .{momentum}); var res = try std.fmt.bufPrint(&buf, "{d}", .{accel});
try std.testing.expectEqualStrings("(9.81, 9.81, 9.81)m.ns⁻²", res);
res = try std.fmt.bufPrint(&buf, "{d:.2}", .{momentum});
try std.testing.expectEqualStrings("(43.00, 0.00, 11.00)m.kg.s⁻¹", res);
} }
test "VecX Init and Basic Arithmetic" { test "VecX Init and Basic Arithmetic" {
@@ -265,12 +283,6 @@ test "VecX Element-wise Math and Scaling" {
try std.testing.expectEqual(4, div.data[1]); try std.testing.expectEqual(4, div.data[1]);
try std.testing.expectEqual(3, div.data[2]); try std.testing.expectEqual(3, div.data[2]);
try std.testing.expectEqual(0, @TypeOf(div).dims.get(.L)); // M / M = Dimensionless try std.testing.expectEqual(0, @TypeOf(div).dims.get(.L)); // M / M = Dimensionless
// Scale by primitive
const scaled = v1.scale(2);
try std.testing.expectEqual(20, scaled.data[0]);
try std.testing.expectEqual(40, scaled.data[1]);
try std.testing.expectEqual(60, scaled.data[2]);
} }
test "VecX Conversions" { test "VecX Conversions" {
@@ -304,124 +316,3 @@ test "VecX Length" {
try std.testing.expectApproxEqAbs(@as(f32, 25.0), v_float.lengthSqr(), 1e-4); try std.testing.expectApproxEqAbs(@as(f32, 25.0), v_float.lengthSqr(), 1e-4);
try std.testing.expectApproxEqAbs(@as(f32, 5.0), v_float.length(), 1e-4); try std.testing.expectApproxEqAbs(@as(f32, 5.0), v_float.length(), 1e-4);
} }
test "Benchmark Vector ops" {
const Io = std.Io;
const ITERS: usize = 10_000;
const SAMPLES: usize = 10;
var gsink: f64 = 0;
// In Zig 0.14+, we use the testing IO for clock access in tests
const io = std.testing.io;
const getTime = struct {
fn f(i: Io) Io.Timestamp {
return Io.Clock.awake.now(i);
}
}.f;
const getVal = struct {
fn f(comptime TT: type, i: usize, comptime mask: u7) TT {
const v: u8 = @as(u8, @truncate(i & @as(usize, mask))) + 1;
return if (comptime @typeInfo(TT) == .float) @floatFromInt(v) else @intCast(v);
}
}.f;
const fold = struct {
fn f(comptime TT: type, s: *f64, v: TT) void {
s.* += if (comptime @typeInfo(TT) == .float)
@as(f64, @floatCast(v))
else
@as(f64, @floatFromInt(v));
}
}.f;
const computeStats = struct {
fn f(samples: []f64, iters: usize) f64 {
std.mem.sort(f64, samples, {}, std.sort.asc(f64));
const mid = samples.len / 2;
const median_ns = if (samples.len % 2 == 0)
(samples[mid - 1] + samples[mid]) / 2.0
else
samples[mid];
return median_ns / @as(f64, @floatFromInt(iters));
}
}.f;
std.debug.print(
\\
\\ Vector<N, T> benchmark — {d} iterations, {d} samples/cell
\\ (Results in ns/op)
\\
\\┌─────────────┬──────┬─────────┬─────────┬─────────┐
\\│ Operation │ Type │ Len=3 │ Len=4 │ Len=16 │
\\├─────────────┼──────┼─────────┼─────────┼─────────┤
\\
, .{ ITERS, SAMPLES });
const Types = .{ i32, i64, i128, f32, f64 };
const TNames = .{ "i32", "i64", "i128", "f32", "f64" };
const Lengths = .{ 3, 4, 16 };
const Ops = .{ "add", "scale", "mulByScalar", "length" };
inline for (Ops, 0..) |op_name, o_idx| {
inline for (Types, TNames) |T, tname| {
std.debug.print("│ {s:<11} │ {s:<4} │", .{ op_name, tname });
inline for (Lengths) |len| {
const Q_base = Scalar(T, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Q_time = Scalar(T, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const V = Vector(len, Q_base);
var samples: [SAMPLES]f64 = undefined;
for (0..SAMPLES) |s_idx| {
var sink: T = 0;
const t_start = getTime(io);
for (0..ITERS) |i| {
const v1 = V.initDefault(getVal(T, i, 63));
if (comptime std.mem.eql(u8, op_name, "add")) {
const v2 = V.initDefault(getVal(T, i +% 7, 63));
const res = v1.add(v2);
for (res.data) |val| {
if (comptime @typeInfo(T) == .float) sink += val else sink ^= val;
}
} else if (comptime std.mem.eql(u8, op_name, "scale")) {
const sc = getVal(T, i +% 2, 63);
const res = v1.scale(sc);
for (res.data) |val| {
if (comptime @typeInfo(T) == .float) sink += val else sink ^= val;
}
} else if (comptime std.mem.eql(u8, op_name, "mulByScalar")) {
const s_val = Q_time{ .value = getVal(T, i +% 2, 63) };
const res = v1.mulByScalar(s_val);
for (res.data) |val| {
if (comptime @typeInfo(T) == .float) sink += val else sink ^= val;
}
} else if (comptime std.mem.eql(u8, op_name, "length")) {
const r = v1.length();
if (comptime @typeInfo(T) == .float) sink += r else sink ^= r;
}
}
const t_end = getTime(io);
samples[s_idx] = @as(f64, @floatFromInt(t_start.durationTo(t_end).toNanoseconds()));
fold(T, &gsink, sink);
}
const median_ns_per_op = computeStats(&samples, ITERS);
std.debug.print(" {d:>7.1} │", .{median_ns_per_op});
}
std.debug.print("\n", .{});
}
if (o_idx < Ops.len - 1) {
std.debug.print("├─────────────┼──────┼─────────┼─────────┼─────────┤\n", .{});
}
}
std.debug.print("└─────────────┴──────┴─────────┴─────────┴─────────┘\n", .{});
std.debug.print("\nAnti-optimisation sink: {d:.4}\n", .{gsink});
try std.testing.expect(gsink != 0);
}
+429
View File
@@ -0,0 +1,429 @@
const std = @import("std");
const Io = std.Io;
const Scalar = @import("Scalar.zig").Scalar;
const Vector = @import("Vector.zig").Vector;
var io: Io = undefined;
pub fn main(init: std.process.Init) !void {
var stdout_buf: [4096]u8 = undefined;
var stdout_writer: std.Io.File.Writer = .init(.stdout(), init.io, &stdout_buf);
try stdout_writer.interface.print("Starting Benchmarks...", .{});
io = init.io;
try bench_Scalar(&stdout_writer.interface);
try stdout_writer.flush();
try bench_vsNative(&stdout_writer.interface);
try stdout_writer.flush();
try bench_crossTypeVsNative(&stdout_writer.interface);
try stdout_writer.flush();
try bench_Vector(&stdout_writer.interface);
try stdout_writer.flush();
}
fn getTime() Io.Timestamp {
return Io.Clock.awake.now(io);
}
fn fold(comptime TT: type, s: *f64, v: TT) void {
s.* += if (comptime @typeInfo(TT) == .float)
@as(f64, @floatCast(v))
else
@as(f64, @floatFromInt(v));
}
fn bench_Scalar(writer: *std.Io.Writer) !void {
const ITERS: usize = 100_000;
const SAMPLES: usize = 10;
const getVal = struct {
fn f(comptime TT: type, i: usize, comptime mask: u7) TT {
const v: u8 = @as(u8, @truncate(i & @as(usize, mask))) + 1;
return if (comptime @typeInfo(TT) == .float) @floatFromInt(v) else @intCast(v);
}
}.f;
const Stats = struct {
median: f64,
delta: f64,
ops_per_sec: f64,
};
const computeStats = struct {
fn f(samples: []f64, iters: usize) Stats {
std.mem.sort(f64, samples, {}, std.sort.asc(f64));
const mid = samples.len / 2;
const median_ns = if (samples.len % 2 == 0) (samples[mid - 1] + samples[mid]) / 2.0 else samples[mid];
const low = samples[0];
const high = samples[samples.len - 1];
const delta_ns = (high - low) / 2.0;
const ns_per_op = median_ns / @as(f64, @floatFromInt(iters));
return .{
.median = ns_per_op,
.delta = (delta_ns / @as(f64, @floatFromInt(iters))),
.ops_per_sec = 1_000_000_000.0 / ns_per_op,
};
}
}.f;
try writer.print(
\\
\\ Scalar<T> benchmark — {d} iterations, {d} samples/cell
\\
\\┌───────────────────┬──────┬─────────────────────┬─────────────────────┐
\\│ Operation │ Type │ ns / op (± delta) │ Throughput (ops/s) │
\\├───────────────────┼──────┼─────────────────────┼─────────────────────┤
\\
, .{ ITERS, SAMPLES });
const Types = .{ i16, i32, i64, i128, i256, f32, f64, f128 };
const TNames = .{ "i16", "i32", "i64", "i128", "i256", "f32", "f64", "f128" };
const Ops = .{ "add", "sub", "mulBy", "divBy", "to" };
var results_matrix: [Ops.len][Types.len]f64 = undefined;
comptime var tidx: usize = 0;
inline for (Types, TNames) |T, tname| {
const M = Scalar(T, .init(.{ .L = 1 }), .init(.{}));
const KM = Scalar(T, .init(.{ .L = 1 }), .init(.{ .L = .k }));
const S = Scalar(T, .init(.{ .T = 1 }), .init(.{}));
inline for (Ops, 0..) |op_name, oidx| {
var samples: [SAMPLES]f64 = undefined;
for (0..SAMPLES) |s_idx| {
const t_start = getTime();
for (0..ITERS) |i| {
std.mem.doNotOptimizeAway(
{
_ = if (comptime std.mem.eql(u8, op_name, "add"))
(M{ .value = getVal(T, i, 63) }).add(M{ .value = getVal(T, i +% 7, 63) })
else if (comptime std.mem.eql(u8, op_name, "sub"))
(M{ .value = getVal(T, i +% 10, 63) }).sub(M{ .value = getVal(T, i, 63) })
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
(M{ .value = getVal(T, i, 63) }).mulBy(M{ .value = getVal(T, i +% 1, 63) })
else if (comptime std.mem.eql(u8, op_name, "divBy"))
(M{ .value = getVal(T, i +% 10, 63) }).divBy(S{ .value = getVal(T, i, 63) })
else
(KM{ .value = getVal(T, i, 15) }).to(M);
},
);
}
const t_end = getTime();
samples[s_idx] = @as(f64, @floatFromInt(t_start.durationTo(t_end).toNanoseconds()));
}
const stats = computeStats(&samples, ITERS);
results_matrix[oidx][tidx] = stats.median;
try writer.print("│ {s:<17} │ {s:<4} │ {d:>8.2} ns ±{d:<6.2} │ {d:>19.0} │\n", .{ op_name, tname, stats.median, stats.delta, stats.ops_per_sec });
}
if (comptime tidx < Types.len - 1) {
try writer.print("├───────────────────┼──────┼─────────────────────┼─────────────────────┤\n", .{});
}
tidx += 1;
}
// Median Summary Table
try writer.print("└───────────────────┴──────┴─────────────────────┴─────────────────────┘\n\n", .{});
try writer.print("Median Summary (ns/op):\n", .{});
try writer.print("┌──────────────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┐\n", .{});
try writer.print("│ Operation │ i16 │ i32 │ i64 │ i128 │ i256 │ f32 │ f64 │ f128 │\n", .{});
try writer.print("├──────────────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┤\n", .{});
inline for (Ops, 0..) |op_name, oidx| {
try writer.print("│ {s:<11} │", .{op_name});
var i: usize = 0;
while (i < Types.len) : (i += 1)
try writer.print("{d:>6.1} │", .{results_matrix[oidx][i]});
try writer.print("\n", .{});
}
try writer.print("└──────────────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┘\n", .{});
}
fn bench_vsNative(writer: *std.Io.Writer) !void {
const ITERS: usize = 100_000;
const SAMPLES: usize = 5;
// Helper to safely get a value of type T from a loop index
const getValT = struct {
fn f(comptime TT: type, i: usize) TT {
const v = (i % 100) + 1;
return if (comptime @typeInfo(TT) == .float) @floatFromInt(v) else @intCast(v);
}
}.f;
const Types = .{ i32, i64, i128, f32, f64 };
const TNames = .{ "i32", "i64", "i128", "f32", "f64" };
const Ops = .{ "add", "mulBy", "divBy" };
try writer.print(
\\
\\ Scalar vs Native Overhead Analysis
\\
\\┌───────────┬──────┬───────────┬───────────┬───────────┐
\\│ Operation │ Type │ Native │ Scalar │ Slowdown │
\\├───────────┼──────┼───────────┼───────────┼───────────┤
\\
, .{});
inline for (Ops, 0..) |op_name, j| {
inline for (Types, 0..) |T, tidx| {
var native_total_ns: f64 = 0;
var quantity_total_ns: f64 = 0;
const M = Scalar(T, .init(.{ .L = 1 }), .init(.{}));
const S = Scalar(T, .init(.{ .T = 1 }), .init(.{}));
std.mem.doNotOptimizeAway({
for (0..SAMPLES) |_| {
// --- 1. Benchmark Native ---
const n_start = getTime();
for (0..ITERS) |i| {
const a = getValT(T, i);
const b = getValT(T, 2);
_ = if (comptime std.mem.eql(u8, op_name, "add"))
a + b
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
a * b
else if (comptime @typeInfo(T) == .int) @divTrunc(a, b) else a / b;
}
const n_end = getTime();
native_total_ns += @as(f64, @floatFromInt(n_start.durationTo(n_end).toNanoseconds()));
// --- 2. Benchmark Scalar ---
const q_start = getTime();
for (0..ITERS) |i| {
const qa = M{ .value = getValT(T, i) };
const qb = if (comptime std.mem.eql(u8, op_name, "divBy")) S{ .value = getValT(T, 2) } else M{ .value = getValT(T, 2) };
_ = if (comptime std.mem.eql(u8, op_name, "add"))
qa.add(qb)
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
qa.mulBy(qb)
else
qa.divBy(qb);
}
const q_end = getTime();
quantity_total_ns += @as(f64, @floatFromInt(q_start.durationTo(q_end).toNanoseconds()));
}
});
const avg_n = (native_total_ns / SAMPLES) / @as(f64, @floatFromInt(ITERS));
const avg_q = (quantity_total_ns / SAMPLES) / @as(f64, @floatFromInt(ITERS));
const slowdown = avg_q / avg_n;
try writer.print("│ {s:<9} │ {s:<4} │ {d:>7.2}ns │ {d:>7.2}ns │ {d:>8.2}x │\n", .{
op_name, TNames[tidx], avg_n, avg_q, slowdown,
});
}
if (j != Ops.len - 1) try writer.print("├───────────┼──────┼───────────┼───────────┼───────────┤\n", .{});
}
try writer.print("└───────────┴──────┴───────────┴───────────┴───────────┘\n", .{});
}
fn bench_crossTypeVsNative(writer: *std.Io.Writer) !void {
const ITERS: usize = 100_000;
const SAMPLES: usize = 5;
const getValT = struct {
fn f(comptime TT: type, i: usize) TT {
// Keep values safe and non-zero to avoid division by zero or overflows during cross-casting
const v = (i % 50) + 1;
return if (comptime @typeInfo(TT) == .float) @floatFromInt(v) else @intCast(v);
}
}.f;
// Helper for the Native baseline: explicitly casting T2 to T1 before the operation
const castTo = struct {
fn f(comptime DestT: type, comptime SrcT: type, val: SrcT) DestT {
if (comptime DestT == SrcT) return val;
const src_info = @typeInfo(SrcT);
const dest_info = @typeInfo(DestT);
if (dest_info == .int and src_info == .int) return @intCast(val);
if (dest_info == .float and src_info == .int) return @floatFromInt(val);
if (dest_info == .int and src_info == .float) return @intFromFloat(val);
if (dest_info == .float and src_info == .float) return @floatCast(val);
unreachable;
}
}.f;
const Types = .{ i16, i64, i128, f32, f64 };
const TNames = .{ "i16", "i64", "i128", "f32", "f64" };
const Ops = .{ "add", "mulBy", "divBy" };
try writer.print(
\\
\\ Cross-Type Overhead Analysis: Scalar vs Native
\\
\\┌─────────┬──────┬──────┬───────────┬───────────┬───────────┐
\\│ Op │ T1 │ T2 │ Native │ Scalar │ Slowdown │
\\├─────────┼──────┼──────┼───────────┼───────────┼───────────┤
\\
, .{});
inline for (Ops, 0..) |op_name, j| {
inline for (Types, 0..) |T1, t1_idx| {
inline for (Types, 0..) |T2, t2_idx| {
var native_total_ns: f64 = 0;
var quantity_total_ns: f64 = 0;
const M1 = Scalar(T1, .init(.{ .L = 1 }), .init(.{}));
const M2 = Scalar(T2, .init(.{ .L = 1 }), .init(.{}));
const S2 = Scalar(T2, .init(.{ .T = 1 }), .init(.{}));
std.mem.doNotOptimizeAway({
for (0..SAMPLES) |_| {
// --- 1. Benchmark Native (Cast T2 to T1, then math) ---
const n_start = getTime();
for (0..ITERS) |i| {
const a = getValT(T1, i);
const b_raw = getValT(T2, 2);
const b = castTo(T1, T2, b_raw);
_ = if (comptime std.mem.eql(u8, op_name, "add"))
a + b
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
a * b
else if (comptime @typeInfo(T1) == .int)
@divTrunc(a, b)
else
a / b;
}
const n_end = getTime();
native_total_ns += @as(f64, @floatFromInt(n_start.durationTo(n_end).toNanoseconds()));
// --- 2. Benchmark Scalar ---
const q_start = getTime();
for (0..ITERS) |i| {
const qa = M1{ .value = getValT(T1, i) };
const qb = if (comptime std.mem.eql(u8, op_name, "divBy"))
S2{ .value = getValT(T2, 2) }
else
M2{ .value = getValT(T2, 2) };
_ = if (comptime std.mem.eql(u8, op_name, "add"))
qa.add(qb)
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
qa.mulBy(qb)
else
qa.divBy(qb);
}
const q_end = getTime();
quantity_total_ns += @as(f64, @floatFromInt(q_start.durationTo(q_end).toNanoseconds()));
}
const avg_n = (native_total_ns / SAMPLES) / @as(f64, @floatFromInt(ITERS));
const avg_q = (quantity_total_ns / SAMPLES) / @as(f64, @floatFromInt(ITERS));
const slowdown = avg_q / avg_n;
try writer.print("│ {s:<7} │ {s:<4} │ {s:<4} │ {d:>7.2}ns │ {d:>7.2}ns │ {d:>8.2}x │\n", .{
op_name, TNames[t1_idx], TNames[t2_idx], avg_n, avg_q, slowdown,
});
});
}
}
if (j != Ops.len - 1) {
try writer.print("├─────────┼──────┼──────┼───────────┼───────────┼───────────┤\n", .{});
}
}
try writer.print("└─────────┴──────┴──────┴───────────┴───────────┴───────────┘\n", .{});
}
fn bench_Vector(writer: *std.Io.Writer) !void {
const ITERS: usize = 10_000;
const SAMPLES: usize = 10;
const getVal = struct {
fn f(comptime TT: type, i: usize, comptime mask: u7) TT {
const v: u8 = @as(u8, @truncate(i & @as(usize, mask))) + 1;
return if (comptime @typeInfo(TT) == .float) @floatFromInt(v) else @intCast(v);
}
}.f;
const computeStats = struct {
fn f(samples: []f64, iters: usize) f64 {
std.mem.sort(f64, samples, {}, std.sort.asc(f64));
const mid = samples.len / 2;
const median_ns = if (samples.len % 2 == 0)
(samples[mid - 1] + samples[mid]) / 2.0
else
samples[mid];
return median_ns / @as(f64, @floatFromInt(iters));
}
}.f;
try writer.print(
\\
\\ Vector<N, T> benchmark — {d} iterations, {d} samples/cell
\\ (Results in ns/op)
\\
\\┌─────────────┬──────┬─────────┬─────────┬─────────┐
\\│ Operation │ Type │ Len=3 │ Len=4 │ Len=16 │
\\├─────────────┼──────┼─────────┼─────────┼─────────┤
\\
, .{ ITERS, SAMPLES });
const Types = .{ i32, i64, i128, f32, f64 };
const TNames = .{ "i32", "i64", "i128", "f32", "f64" };
const Lengths = .{ 3, 4, 16 };
const Ops = .{ "add", "divBy", "mulByScalar", "length" };
inline for (Ops, 0..) |op_name, o_idx| {
inline for (Types, TNames) |T, tname| {
try writer.print("│ {s:<11} │ {s:<4} │", .{ op_name, tname });
inline for (Lengths) |len| {
const Q_base = Scalar(T, .init(.{ .L = 1 }), .init(.{}));
const Q_time = Scalar(T, .init(.{ .T = 1 }), .init(.{}));
const V = Vector(len, Q_base);
var samples: [SAMPLES]f64 = undefined;
std.mem.doNotOptimizeAway({
for (0..SAMPLES) |s_idx| {
const t_start = getTime();
for (0..ITERS) |i| {
const v1 = V.initDefault(getVal(T, i, 63));
if (comptime std.mem.eql(u8, op_name, "add")) {
const v2 = V.initDefault(getVal(T, i +% 7, 63));
_ = v1.add(v2);
} else if (comptime std.mem.eql(u8, op_name, "divBy")) {
_ = v1.divBy(V.initDefault(getVal(T, i +% 2, 63)));
} else if (comptime std.mem.eql(u8, op_name, "mulByScalar")) {
const s_val = Q_time{ .value = getVal(T, i +% 2, 63) };
_ = v1.mulByScalar(s_val);
} else if (comptime std.mem.eql(u8, op_name, "length")) {
_ = v1.length();
}
}
const t_end = getTime();
samples[s_idx] = @as(f64, @floatFromInt(t_start.durationTo(t_end).toNanoseconds()));
}
const median_ns_per_op = computeStats(&samples, ITERS);
try writer.print(" {d:>7.1} │", .{median_ns_per_op});
});
}
try writer.print("\n", .{});
}
if (o_idx < Ops.len - 1) {
try writer.print("├─────────────┼──────┼─────────┼─────────┼─────────┤\n", .{});
}
}
try writer.print("└─────────────┴──────┴─────────┴─────────┴─────────┘\n", .{});
}