gpt4 book ai didi

go - golang时间对象中有多少字节

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:19 25 4
gpt4 key购买 nike

我必须在我正在处理的 go 项目中将时间对象存储在字节数组中,并且必须预先声明数组的大小。我找不到在任何地方引用的字节长度。此时,我计划使用时间库中的 time.MarshalBinary() 将其转换为字节并手动计算出来。但我想知道是否有人对这是字节数有任何引用,以及 time.MarshalBinary() 是否是用于转换为字节的最佳方法。

最佳答案

这个问题的答案并不像看起来那么简单。这在很大程度上取决于您需要在编码中保留多少细节。

正如在另一个答案中指出的,您可以简单地使用 unsafe.Sizeof() 来确定时间对象的内存大小,但这与实际编码的大小几乎没有相似之处,因为它包含一个指针的简单原因。如果我们查看 time.Time 的定义,我们会看到:

type Time struct {
// wall and ext encode the wall time seconds, wall time nanoseconds,
// and optional monotonic clock reading in nanoseconds.
//
// From high to low bit position, wall encodes a 1-bit flag (hasMonotonic),
// a 33-bit seconds field, and a 30-bit wall time nanoseconds field.
// The nanoseconds field is in the range [0, 999999999].
// If the hasMonotonic bit is 0, then the 33-bit field must be zero
// and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext.
// If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit
// unsigned wall seconds since Jan 1 year 1885, and ext holds a
// signed 64-bit monotonic clock reading, nanoseconds since process start.
wall uint64
ext int64

// loc specifies the Location that should be used to
// determine the minute, hour, month, day, and year
// that correspond to this Time.
// The nil location means UTC.
// All UTC times are represented with loc==nil, never loc==&utcLoc.
loc *Location
}

您是否关心存储在 loc 中的时区信息取决于应用程序。如果你总是存储 UTC 时间(通常是最好的方法),那么你可以完全忽略这个位,这意味着你可以通过只存储两个 uint64 来获得。

但即使这两个字段也取决于您是否使用单调时钟。编码数据时,您几乎肯定不会关心单调时钟,无论它是否编码在这些位中。

这意味着,在大多数情况下,您应该能够以 64 位(8 字节)存储一个完整的时间对象,并在必要时加上一个时区指示符。

此外,根据您需要的精度,您可以只存储秒字段(丢弃亚秒级精度),它只需要 33 位。如果您只关心几分钟或几天,您可以使用更少的空间。

关于go - golang时间对象中有多少字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56963226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com