登录
首页 >  Golang >  Go问答

golang时间对象有多少字节

来源:stackoverflow

时间:2024-04-15 08:12:33 213浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《golang时间对象有多少字节》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我必须将时间对象存储在我正在处理的 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 时间(通常是最好的方法),那么您可以完全忽略这一点,这意味着您可以通过仅存储两个 uint64s 来获得。

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

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

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

您可以使用 usafe.Sizeof 获取变量的大小(以字节为单位)。我这样做了

package main

import (
    "fmt"
    "time"
    "unsafe"
)

func main() {
    t := time.Now()
    fmt.Printf("a: %T, %d\n", t, unsafe.Sizeof(t))
}

看起来是 24 字节! :)

marshalbinary 看起来也可以工作,尽管这取决于您发送它的位置以及您想要如何解组它。如果您在 javascript 或其他内容中使用它,那么将其简单地转换为字符串然后使用它可能会更容易。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《golang时间对象有多少字节》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>