github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/twinj/uuid/timestamp.go (about) 1 package uuid 2 3 /**************** 4 * Date: 14/02/14 5 * Time: 7:46 PM 6 ***************/ 7 8 import ( 9 "time" 10 ) 11 12 const ( 13 // A tick is 100 ns 14 ticksPerSecond = 10000000 15 16 // Difference between 17 gregorianToUNIXOffset uint64 = 0x01B21DD213814000 18 19 // set the following to the number of 100ns ticks of the actual 20 // resolution of your system's clock 21 idsPerTimestamp = 1024 22 ) 23 24 var ( 25 lastTimestamp Timestamp 26 idsThisTimestamp = idsPerTimestamp 27 ) 28 29 // ********************************************** Timestamp 30 31 type Timestamp uint64 32 33 // TODO Create c version same as package runtime and time 34 func Now() (sec int64, nsec int32) { 35 t := time.Now() 36 sec = t.Unix() 37 nsec = int32(t.Nanosecond()) 38 return 39 } 40 41 // Converts Unix formatted time to RFC4122 UUID formatted times 42 // UUID UTC base time is October 15, 1582. 43 // Unix base time is January 1, 1970. 44 // Converts time to 100 nanosecond ticks since epoch 45 // There are 1000000000 nanoseconds in a second, 46 // 1000000000 / 100 = 10000000 tiks per second 47 func timestamp() Timestamp { 48 sec, nsec := Now() 49 return Timestamp(uint64(sec)*ticksPerSecond + 50 uint64(nsec)/100 + gregorianToUNIXOffset) 51 } 52 53 func (o Timestamp) Unix() time.Time { 54 t := uint64(o) - gregorianToUNIXOffset 55 return time.Unix(0, int64(t*100)) 56 } 57 58 // Get time as 60-bit 100ns ticks since UUID epoch. 59 // Compensate for the fact that real clock resolution is 60 // less than 100ns. 61 func currentUUIDTimestamp() Timestamp { 62 var timeNow Timestamp 63 for { 64 timeNow = timestamp() 65 66 // if clock reading changed since last UUID generated 67 if lastTimestamp != timeNow { 68 // reset count of UUIDs with this timestamp 69 idsThisTimestamp = 0 70 lastTimestamp = timeNow 71 break 72 } 73 if idsThisTimestamp < idsPerTimestamp { 74 idsThisTimestamp++ 75 break 76 } 77 // going too fast for the clock; spin 78 } 79 // add the count of UUIDs to low order bits of the clock reading 80 return timeNow + Timestamp(idsThisTimestamp) 81 }