Language
Odin
Current Implementation
package main
import "core:fmt"
import "core:os"
import "core:strconv"
import "core:strings"
main :: proc() {
data, ok := os.read_entire_file("rounds.txt")
if !ok {
fmt.eprintln("Failed to read rounds.txt")
return
}
rounds := strconv.atoi(strings.trim_space(string(data)))
pi: f64 = 1.0
x: f64 = 1.0
for i in 2 ..= rounds + 1 {
x = -x
pi += x / f64(2 * i - 1)
}
pi *= 4.0
fmt.printf("%.16f\n", pi)
}
Proposed Implementation
package main
import "core:fmt"
import "core:os"
parse_int :: proc(buf: []u8) -> int{
n := 0
for b in buf {
if b < '0' || b > '9' {
break
}
n = n*10 + int(b - '0')
}
return n
}
main :: proc() {
data, ok := os.read_entire_file("rounds.txt")
if !ok {
fmt.eprintln("Failed to read rounds.txt")
return
}
rounds := parse_int(data)
pi: f64 = 1.0
x: f64 = 1.0
for i in 2 ..= rounds + 1 {
x = -x
pi += x / f64(2 * i - 1)
}
pi *= 4.0
buf: [64]u8
s := fmt.bprintf(buf[:], "%.16f\n", pi)
os.write(os.stdout, buf[:len(s)])
}
// odin build leibniz.odin -file -o:speed -no-bounds-check -disable-assert
Explanation
- Operates directly on a byte slice ([]u8), no conversion to string
- No heap allocations
- Avoids extra string operations like trimming spaces
- Writes directly to a stack-allocated buffer instead of using printf
- Fully optimized by compiler flags (-no-bounds-check, -disable-assert)
Expected Speedup
~20% Faster
Benchmark Results
Current: ~35ms
Proposed ~27ms
odin build leibniz.odin -file -o:speed -no-bounds-check -disable-assert
Optimization Rules
Language
Odin
Current Implementation
Proposed Implementation
Explanation
Expected Speedup
~20% Faster
Benchmark Results
Optimization Rules