github.com/goki/ki@v1.1.17/nptime/nptime.go (about)

     1  // Copyright (c) 2018, The GoKi Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  /*
     6  Package nptime provides a non-pointer version of the time.Time struct
     7  that does not have the location pointer information that time.Time has,
     8  which is more efficient from a memory management perspective, in cases
     9  where you have a lot of time values being kept: https://segment.com/blog/allocation-efficiency-in-high-performance-go-services/
    10  */
    11  package nptime
    12  
    13  import "time"
    14  
    15  // Time represents the value of time.Time without using any pointers for the
    16  // location information, so it is more memory efficient when lots of time
    17  // values are being stored.
    18  type Time struct {
    19  
    20  	// time.Time.Unix() seconds since 1970
    21  	Sec int64 `desc:"time.Time.Unix() seconds since 1970"`
    22  
    23  	// time.Time.Nanosecond() -- nanosecond offset within second, *not* UnixNano()
    24  	NSec uint32 `desc:"time.Time.Nanosecond() -- nanosecond offset within second, *not* UnixNano()"`
    25  }
    26  
    27  // TimeZero is the uninitialized zero time value -- use to check whether
    28  // time has been set or not
    29  var TimeZero Time
    30  
    31  // IsZero returns true if the time is zero and has not been initialized
    32  func (t Time) IsZero() bool {
    33  	return t == TimeZero
    34  }
    35  
    36  // Time returns the time.Time value for this nptime.Time value
    37  func (t Time) Time() time.Time {
    38  	return time.Unix(t.Sec, int64(t.NSec))
    39  }
    40  
    41  // SetTime sets the nptime.Time value based on the time.Time value
    42  func (t *Time) SetTime(tt time.Time) {
    43  	t.Sec = tt.Unix()
    44  	t.NSec = uint32(tt.Nanosecond())
    45  }
    46  
    47  // Now sets the time value to time.Now()
    48  func (t *Time) Now() {
    49  	t.SetTime(time.Now())
    50  }