Reputation: 3221
I'm trying to read a file from stdin in zig but my approach seems a bit slow. So far I have:
var reader = std.io.getStdIn().reader();
var count: u32 = 0;
var buf: [1000]u8 = undefined;
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
_ = line;
count += 1;
}
Ive tried compiling with zig build -Doptimize=ReleaseFast
, however reading a 10k line file using less test.sam | time zig-test
takes around 1.2s, whilst using less test.sam | time wc -l
takes 0.04s. Output of time command for zig-test was:
0.52s user 0.72s system 99% cpu 1.254 total
Seems to be a lot of time spent in both system call and user.
Reading the file directly using this code reduced the time to a more reasonable 0.12s:
var file = try std.fs.cwd().openFile("test.sam", .{});
defer file.close();
var buf_reader = std.io.bufferedReader(file.reader());
var reader = buf_reader.reader();
var count: u32 = 0;
var buf: [10000]u8 = undefined;
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
_ = line;
count += 1;
}
Time output was:
0.13s user 0.00s system 98% cpu 0.133 total
Upvotes: 4
Views: 4912
Reputation: 642
You want to add buffering probably: https://zig.news/kristoff/how-to-add-buffering-to-a-writer-reader-in-zig-7jd
Upvotes: 1