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 read a cached monotonic clock refreshed by a background goroutine about every millisecond, so a timestamp is a single atomic load — roughly 5-6x faster than time.Now() — at the cost of up to ~1ms staleness and resolution.
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 ¶
- func Add(t int64, d time.Duration) int64
- func After(d time.Duration) <-chan int64
- func Alphanumeric(n int) string
- func CalibrateWall()
- func Clock() (hour, min, sec int)
- func Date() (year int, month time.Month, day int)
- func Deadline(d time.Duration) int64
- func Elapsed(start int64) int64
- func Float32(args ...float32) float32
- func Float64(args ...float64) float64
- func Int(args ...int) int
- func Int64(args ...int64) int64
- func Intn(n int) int
- func Letters(n int) string
- func Now() int64
- func Seed(s uint64)
- func Since(start int64) time.Duration
- func SinceMs(start int64) float64
- func SinceSec(start int64) float64
- func SinceUs(start int64) float64
- func Sleep(d time.Duration)
- func Tick(d time.Duration) <-chan int64
- func Uint32() uint32
- func Uint64() uint64
- func Uint64n(n uint64) uint64
- func Unix() int64
- func UnixMicro() int64
- func UnixMilli() int64
- func UnixNano() int64
- func Until(deadline int64) time.Duration
- func Weekday() time.Weekday
- type Stopwatch
- type Ticker
- type Timer
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Add ¶
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 ¶
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 ¶
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 ¶
Date returns the current local year, month, and day derived from the fast wall clock.
year, month, day := turbo.Date()
func Deadline ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 a cached monotonic timestamp in nanoseconds. A background goroutine refreshes the cached value about every millisecond (bounded by OS timer granularity), so Now is a single atomic load — roughly 5-6x faster than time.Now() — at the cost of up to ~1ms of staleness and ~1ms resolution. It is therefore unsuitable for measuring sub-millisecond durations.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 cached monotonic clock, so it shares Now's ~1ms staleness and resolution. For long-running processes, call CalibrateWall periodically to account for NTP drift.
ns := turbo.UnixNano()
func Until ¶
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
}
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 ¶
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 ¶
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()
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 ¶
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()
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 ¶
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 ¶
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()
}