turbo

package module
v0.0.0-...-8609f57 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 4, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

README

turbo

Ultra-fast time, random number, and random string operations for Go. Everything is thread-safe — no configuration needed.

go get github.com/guno1928/turbo

Benchmarks

AMD Ryzen 7 5700X, Go 1.26, Windows/amd64. Zero allocations on all time and random number operations.

Time
Function turbo stdlib Speedup
Now() 2.33 ns/op 3.72 ns/op 1.6x
Since() 2.61 ns/op 4.96 ns/op 1.9x
UnixNano() 2.54 ns/op 3.94 ns/op 1.6x
Elapsed() 2.40 ns/op raw int64
SinceMs() 2.40 ns/op float64 ms
Random Numbers
Function turbo stdlib Speedup
Uint64() 1.72 ns/op 4.79 ns/op 2.8x
Uint32() 1.85 ns/op
Int64() 2.50 ns/op 6.43 ns/op 2.6x
Int() 2.56 ns/op
Float64() 2.77 ns/op 6.23 ns/op 2.2x
Float32() 2.73 ns/op
Intn(1000) 2.65 ns/op 7.15 ns/op 2.7x
Uint64n(1000) 3.07 ns/op
Int64(10,1000) 3.74 ns/op ranged
Float64(1.0,100.0) 3.32 ns/op ranged
Random Strings
Function ns/op B/op allocs/op
Letters(16) 27.6 16 1
Letters(32) 37.5 32 1
Alphanumeric(16) 27.6 16 1
Alphanumeric(32) 37.5 32 1
Parallel Scalability (16 cores)
Function turbo stdlib
Uint64() 0.18 ns/op 0.74 ns/op
Letters(16) 9.33 ns/op

API Reference & Examples

1. Monotonic Timestamps
start := turbo.Now() // fast monotonic clock (int64 ns)
// ... work ...
elapsed := turbo.Since(start) // time.Duration
2. Raw Nanosecond Elapsed
start := turbo.Now()
// ... work ...
ns := turbo.Elapsed(start) // raw int64 — no type conversion overhead
3. Human-Friendly Elapsed
start := turbo.Now()
// ... work ...
ms := turbo.SinceMs(start)   // float64 milliseconds
us := turbo.SinceUs(start)   // float64 microseconds
sec := turbo.SinceSec(start) // float64 seconds
4. Deadlines & Timeouts
deadline := turbo.Deadline(5 * time.Second)

for turbo.Until(deadline) > 0 {
    // process items until deadline expires
}
5. Wall-Clock Timestamps
ns := turbo.UnixNano()   // nanoseconds since Unix epoch
us := turbo.UnixMicro()  // microseconds
ms := turbo.UnixMilli()  // milliseconds
s  := turbo.Unix()       // seconds
6. Date, Clock & Weekday
year, month, day := turbo.Date()
hour, min, sec := turbo.Clock()
weekday := turbo.Weekday()
7. Random Numbers
n := turbo.Uint64()        // random uint64
u := turbo.Uint32()        // random uint32
i := turbo.Int64()         // non-negative int64
x := turbo.Int()           // non-negative int
r := turbo.Intn(100)       // [0, 100)
v := turbo.Uint64n(1000)   // [0, 1000)
f := turbo.Float64()       // [0.0, 1.0)
g := turbo.Float32()       // [0.0, 1.0)
8. Ranged Random Numbers
// Int64 and Int accept optional (min, max) for half-open interval [min, max)
n := turbo.Int64(10, 50)       // random int64 in [10, 50)
n = turbo.Int64(-100, 100)     // negative ranges work too

x := turbo.Int(1, 1000)       // random int in [1, 1000)

// Float64 and Float32 accept optional (min, max)
f := turbo.Float64(1.0, 10.0) // random float64 in [1.0, 10.0)
g := turbo.Float32(0.5, 1.5)  // random float32 in [0.5, 1.5)

// Uint64n for [0, n) range
v := turbo.Uint64n(1_000_000) // [0, 1000000)
9. Deterministic Seeding
turbo.Seed(42)          // reproducible sequence (useful in tests)
a := turbo.Uint64()     // always the same after Seed(42)
10. Random Strings
// Upper + lowercase letters (a-z, A-Z)
token := turbo.Letters(32) // e.g. "KjRtBnMpXwLqFhDsYcNeVgUaWoIzJbTm"

// Letters + digits (a-z, A-Z, 0-9)
id := turbo.Alphanumeric(16) // e.g. "K3RtB8MpX2Lq7hDs"
11. Timers
// Fire once after a duration (channel receives turbo.Now() timestamp)
ch := turbo.After(100 * time.Millisecond)
ts := <-ch

// Controllable timer
timer := turbo.NewTimer(5 * time.Second)
// ...
timer.Stop()
timer.Reset(10 * time.Second)

// Run a function after a delay
turbo.AfterFunc(time.Second, func() {
    fmt.Println("fired!")
})
12. Tickers
ticker := turbo.NewTicker(100 * time.Millisecond)
defer ticker.Stop()

for ts := range ticker.C {
    fmt.Printf("tick at %d\n", ts)
}
13. Stopwatch
sw := turbo.NewStopwatch() // starts immediately

// ... work ...
fmt.Println(sw.Elapsed()) // total elapsed time

lap1 := sw.Lap()          // time since last lap/start, resets lap marker
// ... more work ...
lap2 := sw.Lap()

sw.Stop()                  // pause
sw.Start()                 // resume
sw.Reset()                 // stop + zero
sw.Restart()               // zero + start
14. Timestamp Arithmetic
start := turbo.Now()
later := turbo.Add(start, 500*time.Millisecond) // offset a timestamp
remaining := turbo.Until(later)                  // how long until then

Full Public API

Time
Function Returns Description
Now() int64 Monotonic timestamp (ns)
Since(start) time.Duration Duration since start
Until(deadline) time.Duration Duration until deadline
Elapsed(start) int64 Raw ns since start
SinceMs(start) float64 Milliseconds since start
SinceUs(start) float64 Microseconds since start
SinceSec(start) float64 Seconds since start
Deadline(d) int64 Timestamp d in the future
Add(t, d) int64 Timestamp t + duration d
Sleep(d) Sleep for duration d
UnixNano() int64 Wall-clock ns since epoch
UnixMicro() int64 Wall-clock µs since epoch
UnixMilli() int64 Wall-clock ms since epoch
Unix() int64 Wall-clock seconds since epoch
Date() (int, time.Month, int) Current year, month, day
Clock() (int, int, int) Current hour, minute, second
Weekday() time.Weekday Current day of the week
CalibrateWall() Re-sync wall offset (for NTP drift)
Random Numbers
Function Returns Description
Uint64() uint64 Random uint64
Uint32() uint32 Random uint32
Uint64n(n) uint64 Random uint64 in [0, n)
Int64(args...) int64 Non-negative int64, or [min, max) with 2 args
Int(args...) int Non-negative int, or [min, max) with 2 args
Intn(n) int Random int in [0, n)
Float64(args...) float64 Random float in [0, 1), or [min, max) with 2 args
Float32(args...) float32 Random float in [0, 1), or [min, max) with 2 args
Seed(s) Set deterministic seed
Random Strings
Function Returns Description
Letters(n) string Random a-z, A-Z string of length n
Alphanumeric(n) string Random a-z, A-Z, 0-9 string of length n
Timers
Function / Method Returns Description
After(d) <-chan int64 Channel fires once after d
NewTimer(d) *Timer Controllable one-shot timer
AfterFunc(d, f) *Timer Calls f after d
Timer.Stop() bool Cancel timer
Timer.Reset(d) bool Reschedule timer
Tick(d) <-chan int64 Convenience periodic channel
NewTicker(d) *Ticker Controllable periodic ticker
Ticker.Stop() Stop ticker
Ticker.Reset(d) Change ticker interval
Stopwatch
Method Returns Description
NewStopwatch() *Stopwatch Create & start
Start() Start / resume
Stop() time.Duration Pause, return total elapsed
Elapsed() time.Duration Total elapsed (running or stopped)
Lap() time.Duration Split time since last lap
Reset() Stop + zero elapsed
Restart() Zero + start
Running() bool Is it running?

Thread Safety

Every function and method in turbo is safe for concurrent use from any number of goroutines. Random number generation uses stack-address-indexed state with atomic advancement and 64-byte cache-line padding to prevent false sharing — no locks, no runtime.procPin. String generation uses per-P state via runtime.procPin for sequential multi-value extraction. The Stopwatch type uses a mutex internally.

How It Works

  • wyrand algorithm (wyhash family by Wang Yi) — passes BigCrush statistical tests. On amd64, bits.Mul64 compiles to a single MULQ instruction.
  • runtime.nanotime() via go:linkname — reads only the monotonic clock, skipping wall-clock reads and time.Time struct construction.
  • Stack-address indexing — goroutine stack addresses are used to index into a padded state array, with atomic.AddUint64 for thread-safe advancement. This eliminates runtime.procPin/procUnpin overhead entirely, yielding ~1.7 ns/op for Uint64().
  • 256-byte LUT for strings — pre-computed lookup tables with zero rejection sampling, extracting 8 characters per uint64.
  • Lemire's nearly-divisionless algorithm for unbiased range reduction in Intn(), Uint64n(), Int64(min, max), etc.

License

MIT

Documentation

Overview

Package turbo provides ultra-fast time operations, random number generation, and random string generation for performance-critical Go applications.

All functions are safe for concurrent use from any number of goroutines. There are no non-thread-safe options.

Time

Time functions use runtime.nanotime() via go:linkname, bypassing wall-clock reads and time.Time struct construction for ~1.7x faster timestamps.

start := turbo.Now()
// ... work ...
elapsed := turbo.Since(start)       // time.Duration
ms := turbo.SinceMs(start)          // float64 milliseconds
ns := turbo.Elapsed(start)          // raw int64 nanoseconds

Random Numbers

Uses the wyrand algorithm (wyhash family by Wang Yi). On amd64, bits.Mul64 compiles to a single MULQ instruction. Random state is indexed by goroutine stack address with atomic advancement, yielding ~1.7 ns/op with near-zero contention. All random functions accept optional (min, max) range arguments.

n := turbo.Uint64()              // full random uint64
f := turbo.Float64()             // [0.0, 1.0)
i := turbo.Intn(100)             // [0, 100)
r := turbo.Int64(10, 50)         // [10, 50)
v := turbo.Float64(1.0, 10.0)   // [1.0, 10.0)
u := turbo.Uint64n(1000)         // [0, 1000)

Random Strings

Pre-computed 256-byte LUTs with zero rejection sampling, extracting 8 characters per uint64.

s := turbo.Letters(16)          // a-z, A-Z
s = turbo.Alphanumeric(16)     // a-z, A-Z, 0-9

Timers & Stopwatch

timer := turbo.NewTimer(5 * time.Second)
<-timer.C // receives turbo.Now() timestamp

sw := turbo.NewStopwatch()
// ... work ...
fmt.Println(sw.Elapsed())

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Add

func Add(t int64, d time.Duration) int64

Add returns a new monotonic timestamp that is duration d after timestamp t. Useful for computing future deadlines relative to an existing timestamp.

start := turbo.Now()
checkpoint := turbo.Add(start, 500*time.Millisecond)

func After

func After(d time.Duration) <-chan int64

After returns a channel that receives the current monotonic timestamp after duration d. It is equivalent to NewTimer(d).C and is useful for one-shot timeout selects.

select {
case result := <-work:
    handle(result)
case <-turbo.After(5 * time.Second):
    fmt.Println("timeout")
}

func Alphanumeric

func Alphanumeric(n int) string

Alphanumeric returns a random string of length n composed of upper and lowercase ASCII letters plus decimal digits (a-z, A-Z, 0-9). Returns an empty string when n <= 0. Each call allocates exactly one []byte of length n. Safe for concurrent use.

id := turbo.Alphanumeric(16) // e.g. "K3RtB8MpX2Lq7hDs"

func CalibrateWall

func CalibrateWall()

CalibrateWall re-synchronizes the internal wall-clock offset with the system clock. Call this periodically (e.g. every 5 minutes) in long-running processes to compensate for NTP clock adjustments that would otherwise cause UnixNano/UnixMilli/Unix drift.

go func() {
    for range time.Tick(5 * time.Minute) {
        turbo.CalibrateWall()
    }
}()

func Clock

func Clock() (hour, min, sec int)

Clock returns the current local hour, minute, and second derived from the fast wall clock.

hour, min, sec := turbo.Clock()

func Date

func Date() (year int, month time.Month, day int)

Date returns the current local year, month, and day derived from the fast wall clock.

year, month, day := turbo.Date()

func Deadline

func Deadline(d time.Duration) int64

Deadline returns a monotonic timestamp that is duration d in the future. Use with Until to implement timeout loops, or with Since to measure total elapsed.

deadline := turbo.Deadline(5 * time.Second)
for turbo.Until(deadline) > 0 {
    item := queue.Pop()
    process(item)
}

func Elapsed

func Elapsed(start int64) int64

Elapsed returns the raw nanosecond count elapsed since start as an int64. Unlike Since, it does not convert to time.Duration, saving a type conversion on extremely hot paths where every nanosecond counts.

start := turbo.Now()
// ... work ...
ns := turbo.Elapsed(start) // raw int64 nanoseconds

func Float32

func Float32(args ...float32) float32

Float32 returns a pseudorandom float32. Call with zero arguments for a value in [0.0, 1.0), or with two arguments (min, max) for a value in [min, max). Panics if min >= max or if the argument count is not 0 or 2. Safe for concurrent use, zero allocations.

f := turbo.Float32()          // [0.0, 1.0)
f = turbo.Float32(0.5, 1.5)   // [0.5, 1.5)

func Float64

func Float64(args ...float64) float64

Float64 returns a pseudorandom float64. Call with zero arguments for a value in [0.0, 1.0), or with two arguments (min, max) for a value in [min, max). Panics if min >= max or if the argument count is not 0 or 2. Safe for concurrent use, zero allocations.

f := turbo.Float64()          // [0.0, 1.0)
f = turbo.Float64(1.0, 10.0)  // [1.0, 10.0)

func Int

func Int(args ...int) int

Int returns a pseudorandom int. Call with zero arguments for a non-negative random int, or with two arguments (min, max) for a value in the half-open interval [min, max). Panics if min >= max or if the argument count is not 0 or 2. Safe for concurrent use, zero allocations.

n := turbo.Int()        // non-negative random int
n = turbo.Int(1, 100)   // random int in [1, 100)

func Int64

func Int64(args ...int64) int64

Int64 returns a pseudorandom int64. Call with zero arguments for a non-negative random int64, or with two arguments (min, max) for a value in the half-open interval [min, max). Panics if min >= max or if the argument count is not 0 or 2. Safe for concurrent use, zero allocations.

n := turbo.Int64()         // non-negative random int64
n = turbo.Int64(10, 50)    // random int64 in [10, 50)
n = turbo.Int64(-100, 100) // random int64 in [-100, 100)

func Intn

func Intn(n int) int

Intn returns a uniformly distributed pseudorandom int in the half-open interval [0, n). It uses Lemire's nearly-divisionless algorithm for unbiased range reduction. Panics if n <= 0. Safe for concurrent use, zero allocations.

v := turbo.Intn(100) // [0, 100)

func Letters

func Letters(n int) string

Letters returns a random string of length n composed entirely of upper and lowercase ASCII letters (a-z, A-Z). Returns an empty string when n <= 0. Each call allocates exactly one []byte of length n. Safe for concurrent use.

token := turbo.Letters(32) // e.g. "KjRtBnMpXwLqFhDsYcNeVgUaWoIzJbTm"

func Now

func Now() int64

Now returns the current monotonic timestamp in nanoseconds. It reads only the monotonic clock via runtime.nanotime(), skipping wall-clock reads and time.Time struct construction, making it roughly 1.7x faster than time.Now().

The returned int64 is only meaningful for computing durations via subtraction (use Since, Elapsed, SinceMs, etc.) or for deadline comparisons (use Until). For wall-clock timestamps, use UnixNano, UnixMilli, or Unix instead.

start := turbo.Now()
// ... work ...
elapsed := turbo.Since(start)

func Seed

func Seed(s uint64)

Seed sets every PRNG state deterministically from a single seed value s using SplitMix64 derivation. After calling Seed with a given value, subsequent random outputs follow a reproducible, fixed sequence when called from a single goroutine with no concurrent random calls. This is intended for deterministic testing and benchmarking.

turbo.Seed(42)
fmt.Println(turbo.Uint64()) // always the same after Seed(42)

func Since

func Since(start int64) time.Duration

Since returns the wall-clock-independent duration elapsed since the monotonic timestamp start, which should be a value previously returned by Now. Safe for concurrent use, zero allocations.

start := turbo.Now()
time.Sleep(100 * time.Millisecond)
fmt.Println(turbo.Since(start)) // ~100ms

func SinceMs

func SinceMs(start int64) float64

SinceMs returns the milliseconds elapsed since start as a float64. Convenient for logging or human-readable output without manual division.

start := turbo.Now()
// ... work ...
fmt.Printf("took %.3f ms\n", turbo.SinceMs(start))

func SinceSec

func SinceSec(start int64) float64

SinceSec returns the seconds elapsed since start as a float64.

start := turbo.Now()
// ... work ...
fmt.Printf("took %.4f s\n", turbo.SinceSec(start))

func SinceUs

func SinceUs(start int64) float64

SinceUs returns the microseconds elapsed since start as a float64.

start := turbo.Now()
// ... work ...
fmt.Printf("took %.1f µs\n", turbo.SinceUs(start))

func Sleep

func Sleep(d time.Duration)

Sleep pauses the current goroutine for at least duration d. This is a convenience wrapper around time.Sleep for API completeness.

turbo.Sleep(100 * time.Millisecond)

func Tick

func Tick(d time.Duration) <-chan int64

Tick is a convenience wrapper that returns only the channel from a new Ticker. Useful when you do not need to stop the ticker. Returns nil if d <= 0.

for ts := range turbo.Tick(time.Second) {
    fmt.Println("tick", ts)
}

func Uint32

func Uint32() uint32

Uint32 returns a uniformly distributed pseudorandom uint32 derived from the upper 32 bits of a full 64-bit random value. Safe for concurrent use, zero allocations.

n := turbo.Uint32()

func Uint64

func Uint64() uint64

Uint64 returns a uniformly distributed pseudorandom uint64. This is the fastest random function in the package (~1.7 ns/op, zero allocations) and is safe for concurrent use.

n := turbo.Uint64()

func Uint64n

func Uint64n(n uint64) uint64

Uint64n returns a uniformly distributed pseudorandom uint64 in the half-open interval [0, n) using Lemire's nearly-divisionless algorithm for unbiased range reduction. Safe for concurrent use, zero allocations.

v := turbo.Uint64n(1000) // [0, 1000)

func Unix

func Unix() int64

Unix returns the current wall-clock time as seconds since the Unix epoch.

sec := turbo.Unix()

func UnixMicro

func UnixMicro() int64

UnixMicro returns the current wall-clock time as microseconds since the Unix epoch.

us := turbo.UnixMicro()

func UnixMilli

func UnixMilli() int64

UnixMilli returns the current wall-clock time as milliseconds since the Unix epoch.

ms := turbo.UnixMilli()

func UnixNano

func UnixNano() int64

UnixNano returns the current wall-clock time as nanoseconds since the Unix epoch (January 1, 1970 UTC). This is faster than time.Now().UnixNano() because it derives wall time from a cached offset plus the fast monotonic clock. For long-running processes, call CalibrateWall periodically to account for NTP drift.

ns := turbo.UnixNano()

func Until

func Until(deadline int64) time.Duration

Until returns the duration remaining until a monotonic deadline timestamp. Returns a negative duration if the deadline has already passed. Pair with Deadline to implement timeout loops.

deadline := turbo.Deadline(5 * time.Second)
for turbo.Until(deadline) > 0 {
    // keep working until deadline
}

func Weekday

func Weekday() time.Weekday

Weekday returns the current local day of the week derived from the fast wall clock.

wd := turbo.Weekday()

Types

type Stopwatch

type Stopwatch struct {
	// contains filtered or unexported fields
}

Stopwatch measures elapsed time with start/stop/lap support. It accumulates time across multiple Start/Stop cycles and supports split timing via Lap. All methods are safe for concurrent use from multiple goroutines.

sw := turbo.NewStopwatch()
// ... work ...
fmt.Println(sw.Elapsed())
lap1 := sw.Lap()
// ... more work ...
lap2 := sw.Lap()
sw.Stop()

func NewStopwatch

func NewStopwatch() *Stopwatch

NewStopwatch creates a Stopwatch that is already running. Call Elapsed to read accumulated time, Lap for split timing.

sw := turbo.NewStopwatch()

func (*Stopwatch) Elapsed

func (sw *Stopwatch) Elapsed() time.Duration

Elapsed returns the total accumulated elapsed time. If the stopwatch is running, this includes time since the last Start call.

fmt.Println(sw.Elapsed())

func (*Stopwatch) Lap

func (sw *Stopwatch) Lap() time.Duration

Lap returns the time elapsed since the last Lap or Start call, resets the lap marker, and keeps the stopwatch running. Returns 0 if the stopwatch is stopped.

lap1 := sw.Lap()
// ... more work ...
lap2 := sw.Lap()

func (*Stopwatch) Reset

func (sw *Stopwatch) Reset()

Reset stops the stopwatch and zeroes all accumulated time.

func (*Stopwatch) Restart

func (sw *Stopwatch) Restart()

Restart zeroes all accumulated time and starts the stopwatch.

sw.Restart() // equivalent to Reset() + Start()

func (*Stopwatch) Running

func (sw *Stopwatch) Running() bool

Running reports whether the stopwatch is currently running.

func (*Stopwatch) Start

func (sw *Stopwatch) Start()

Start starts or resumes the stopwatch. If already running, Start is a no-op.

func (*Stopwatch) Stop

func (sw *Stopwatch) Stop() time.Duration

Stop pauses the stopwatch and returns the total accumulated elapsed time. If already stopped, it returns the total without modification.

elapsed := sw.Stop()

type Ticker

type Ticker struct {
	C <-chan int64
	// contains filtered or unexported fields
}

Ticker delivers monotonic timestamps on its channel C at regular intervals. It drops ticks to make up for slow receivers. All methods are safe for concurrent use.

ticker := turbo.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for ts := range ticker.C {
    process(ts)
}

func NewTicker

func NewTicker(d time.Duration) *Ticker

NewTicker creates a Ticker that sends the current monotonic timestamp on C every duration d. The ticker drops ticks for slow receivers rather than buffering. Panics if d <= 0.

ticker := turbo.NewTicker(50 * time.Millisecond)
defer ticker.Stop()

func (*Ticker) Reset

func (t *Ticker) Reset(d time.Duration)

Reset changes the ticker period to d. The next tick arrives after the new period. Panics if d <= 0.

func (*Ticker) Stop

func (t *Ticker) Stop()

Stop turns off the ticker. After Stop, no more ticks are sent on C. Safe to call multiple times.

type Timer

type Timer struct {
	C <-chan int64
	// contains filtered or unexported fields
}

Timer fires once after a duration, delivering the current monotonic timestamp (from Now) on its channel C. The channel is buffered with capacity 1, so a single fire is never lost even if no goroutine is receiving at that moment.

timer := turbo.NewTimer(5 * time.Second)
ts := <-timer.C // monotonic nanosecond timestamp
timer.Stop()    // safe even after fire

func AfterFunc

func AfterFunc(d time.Duration, f func()) *Timer

AfterFunc waits for duration d then calls f in its own goroutine. The returned Timer can be used to cancel the call with Stop. The Timer's C channel is nil.

cancel := turbo.AfterFunc(time.Second, func() {
    fmt.Println("fired!")
})
// cancel.Stop() to abort

func NewTimer

func NewTimer(d time.Duration) *Timer

NewTimer creates a Timer that fires once after duration d, sending the monotonic timestamp from Now on C. Use Stop to cancel, Reset to reschedule.

timer := turbo.NewTimer(100 * time.Millisecond)
select {
case ts := <-timer.C:
    fmt.Println("fired at", ts)
case <-ctx.Done():
    timer.Stop()
}

func (*Timer) Reset

func (t *Timer) Reset(d time.Duration) bool

Reset changes the timer to fire after duration d. It returns true if the timer had been active, false if it had already fired or been stopped.

func (*Timer) Stop

func (t *Timer) Stop() bool

Stop prevents the Timer from firing. It returns true if the call stops the timer, false if the timer has already fired or been stopped.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL