fasttime

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: MIT Imports: 7 Imported by: 0

README

fasttime

高性能时间缓存库,通过后台 goroutine 定期更新时间戳来减少系统调用开销,适用于高频时间获取场景。

特性

  • 通过 atomic.Int64 缓存时间,读取零锁、零分配
  • 默认 200ms 更新间隔,可配置高精度模式(10ms)
  • 全部返回 UTC 时间
  • 内置 XID 生成器(兼容 rs/xid 规范)

安装

go get github.com/dnsoa/go/fasttime

使用

时间获取
package main

import (
    "fmt"
    "github.com/dnsoa/go/fasttime"
)

func main() {
    // 替代 time.Now(),性能更高
    now := fasttime.Now()

    // 直接获取 Unix 时间戳(纳秒/秒)
    nano := fasttime.UnixNano()
    sec  := fasttime.UnixTime()

    // 按天/小时聚合
    day  := fasttime.UnixDate()
    hour := fasttime.UnixHour()

    // 时间差计算
    elapsed := fasttime.Since(startTime)
    remain  := fasttime.Until(deadline)
}
XID 生成
// 生成全局唯一 ID(12 字节,20 字符 base32 表示)
id := fasttime.NewXID()
fmt.Println(id.String()) // e.g. "bm55gpjkd48c2qe6l6d0"

// 从时间戳生成
id = fasttime.NewXIDWithTime(time.Now().Unix())

// 解析
id, err := fasttime.ParseXID("bm55gpjkd48c2qe6l6d0")

// 提取字段
id.Time()    // time.Time
id.Machine() // 3 字节机器标识
id.Pid()     // 进程 ID
id.Counter() // 计数器

// 支持 JSON/Text 序列化
data, _ := json.Marshal(id)
json.Unmarshal(data, &id)
高精度模式

设置环境变量启用 10ms 更新间隔:

export FASTTIME_HIGH_PRECISION=true

XID 结构

| 4 字节时间戳 | 3 字节机器 ID | 2 字节 PID | 3 字节计数器 |
  • 时间戳:Unix 秒级时间(大端序)
  • 机器 ID:主机名哈希,获取失败时使用随机字节
  • PID:进程 ID
  • 计数器:随机初始值,原子递增,并发安全

精度说明

模式 更新间隔 适用场景
默认 200ms 日志、监控、ID 生成等毫秒级精度无需保证的场景
高精度 10ms 对时间精度有更高要求的场景

返回的时间可能比实际时间滞后最多一个更新间隔。

性能

相比标准库 time.Now(),避免了每次调用的系统调用开销:

BenchmarkUnixTimestamp   →  ~1ns/op   (fasttime.UnixTime)
BenchmarkTimeNowUnix     →  ~25ns/op  (time.Now().Unix())
BenchmarkUnixNano        →  ~1ns/op   (fasttime.UnixNano)
BenchmarkXID             →  ~3ns/op   (NewXID, 使用缓存时间)

Documentation

Overview

Package fasttime provides a high-performance alternative to time.Now() by caching the current time and updating it periodically in a background goroutine.

The cached time reduces system call overhead significantly, making it suitable for high-frequency operations where exact millisecond precision is not required.

By default, time is updated every 200ms (configurable via FASTTIME_HIGH_PRECISION environment variable). All times are returned in UTC for consistency across distributed systems.

Index

Constants

View Source
const (
	// DefaultUpdateInterval is the default time update interval.
	DefaultUpdateInterval = 200 * time.Millisecond

	// HighPrecisionUpdateInterval is the interval used when FASTTIME_HIGH_PRECISION is set.
	HighPrecisionUpdateInterval = 10 * time.Millisecond

	// SecondsPerDay is the number of seconds in a day.
	SecondsPerDay = 24 * 3600

	// SecondsPerHour is the number of seconds in an hour.
	SecondsPerHour = 3600
)
View Source
const ErrInvalidXID = xidError("xid: invalid XID")

ErrInvalidXID is returned when trying to parse an invalid XID

Variables

This section is empty.

Functions

func Now

func Now() time.Time

Now returns current time in UTC.

func Since

func Since(t time.Time) time.Duration

Since returns the time elapsed since t. It is shorthand for time.Now().Sub(t) but uses the cached time.

Note: If t is in the future, this will return a negative duration. For past times, the result may be up to UpdateInterval ahead of the actual elapsed time.

func UnixDate

func UnixDate() int64

UnixDate returns date from the current unix timestamp.

func UnixHour

func UnixHour() int64

UnixHour returns hour from the current unix timestamp.

func UnixNano

func UnixNano() int64

UnixNano returns the current unix timestamp in nanoseconds. It is faster than time.Now().UnixNano().

func UnixTime

func UnixTime() int64

UnixTime returns the current unix timestamp in seconds.

func Until

func Until(t time.Time) time.Duration

Until returns the duration until t. It is shorthand for t.Sub(time.Now()) but uses the cached time.

Note: If t is in the past, this will return a negative duration. For future times, the result may be up to UpdateInterval less than the actual remaining time.

Types

type XID added in v1.0.3

type XID [12]byte

XID represents a unique request id

func NewXID added in v1.0.3

func NewXID() XID

NewXID generates a globally unique XID

func NewXIDWithTime added in v1.0.3

func NewXIDWithTime(timestamp int64) (x XID)

NewXIDWithTime generates a globally unique XID with unix timestamp

func ParseXID added in v1.0.3

func ParseXID(s string) (x XID, err error)

ParseXID parses an XID from its string representation

func (XID) Counter added in v1.0.3

func (x XID) Counter() uint32

Counter returns the incrementing value part of the id.

func (XID) Machine added in v1.0.3

func (x XID) Machine() []byte

Machine returns the 3-byte machine id part of the id.

func (XID) MarshalJSON added in v1.0.3

func (x XID) MarshalJSON() (dst []byte, err error)

MarshalJSON implements encoding/json Marshaler interface

func (XID) MarshalText added in v1.0.3

func (x XID) MarshalText() (dst []byte, err error)

MarshalText implements encoding/text TextMarshaler interface

func (XID) Pid added in v1.0.3

func (x XID) Pid() uint16

Pid returns the process id part of the id.

func (XID) String added in v1.0.3

func (x XID) String() string

String returns a base32 hex lowercased representation of the id.

func (XID) Time added in v1.0.3

func (x XID) Time() time.Time

Time returns the timestamp part of the id.

func (*XID) UnmarshalJSON added in v1.0.3

func (x *XID) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON implements encoding/json Unmarshaler interface

func (*XID) UnmarshalText added in v1.0.3

func (x *XID) UnmarshalText(text []byte) (err error)

UnmarshalText implements encoding/text TextUnmarshaler interface

Jump to

Keyboard shortcuts

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