Skip to content

Commit e9fbb95

Browse files
committed
Use jemalloc
1 parent d0ff764 commit e9fbb95

File tree

4 files changed

+54
-2
lines changed

4 files changed

+54
-2
lines changed

.github/workflows/build.yml

+2
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ jobs:
3030
- name: Run tests
3131
run: zig build test --summary all
3232

33+
- run: apt-get update && apt-get install -y libjemalloc-dev
34+
3335
- name: Build release binary
3436
run: zig build --release=fast --summary all
3537

Dockerfile

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
FROM ubuntu:24.04
22

3-
RUN apt-get update && apt-get install -y glibc-tools
3+
RUN apt-get update && apt-get install -y glibc-tools libjemalloc2
44

55
RUN useradd -m -s /bin/bash -u 6081 acoustid
66

src/jemalloc.zig

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
const std = @import("std");
2+
const Allocator = std.mem.Allocator;
3+
const c = @cImport({
4+
@cInclude("jemalloc/jemalloc.h");
5+
});
6+
7+
pub const allocator = Allocator{
8+
.ptr = undefined,
9+
.vtable = &.{
10+
.alloc = alloc,
11+
.resize = resize,
12+
.free = free,
13+
},
14+
};
15+
16+
fn alloc(_: *anyopaque, n: usize, log2_align: u8, return_address: usize) ?[*]u8 {
17+
_ = return_address;
18+
19+
const alignment = @as(usize, 1) << @as(Allocator.Log2Align, @intCast(log2_align));
20+
const ptr = c.je_aligned_alloc(alignment, n) orelse return null;
21+
return @ptrCast(ptr);
22+
}
23+
24+
fn resize(
25+
_: *anyopaque,
26+
buf: []u8,
27+
log2_buf_align: u8,
28+
new_len: usize,
29+
return_address: usize,
30+
) bool {
31+
_ = log2_buf_align;
32+
_ = return_address;
33+
34+
if (new_len <= buf.len)
35+
return true;
36+
37+
return new_len <= c.je_malloc_usable_size(buf.ptr);
38+
}
39+
40+
fn free(_: *anyopaque, buf: []u8, log2_buf_align: u8, return_address: usize) void {
41+
_ = log2_buf_align;
42+
_ = return_address;
43+
c.je_free(buf.ptr);
44+
}
45+
46+
test "basic" {
47+
const buf = try allocator.alloc(u8, 256);
48+
defer allocator.free(buf);
49+
}

src/main.zig

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const Scheduler = @import("utils/Scheduler.zig");
77
const MultiIndex = @import("MultiIndex.zig");
88
const server = @import("server.zig");
99
const metrics = @import("metrics.zig");
10+
const jemalloc = @import("jemalloc.zig");
1011

1112
pub const std_options = .{
1213
.log_level = .debug,
@@ -41,7 +42,7 @@ pub fn main() !void {
4142
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{};
4243
defer _ = gpa.deinit();
4344

44-
const allocator = if (builtin.mode == .ReleaseFast and !builtin.is_test) std.heap.c_allocator else gpa.allocator();
45+
const allocator = if (builtin.mode == .ReleaseFast and !builtin.is_test) jemalloc.allocator else gpa.allocator();
4546

4647
var args = try zul.CommandLineArgs.parse(allocator);
4748
defer args.deinit();

0 commit comments

Comments
 (0)