Skip to content

Optimize Odin #261

Description

@Adriwang

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

  • Still single-threaded (no concurrency/parallelism)
  • Still uses the Leibniz formula
  • Produces the same (or more accurate) result
  • Uses standard language features (no inline assembly unless it's a SIMD variant)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions