/
tsc.go
74 lines (62 loc) · 1.67 KB
/
tsc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package eal
/*
#include "../../csrc/dpdk/tsc.h"
*/
import "C"
import (
"time"
)
var (
// TscHz is TSC time units in one second.
TscHz uint64
// TscGHz is TSC time units in one nanosecond.
TscGHz float64
// TscSeconds is seconds in one TSC time unit.
TscSeconds float64
// TscNanos is nanoseconds in one TSC time unit.
TscNanos float64
)
// InitTscUnit saves TSC time unit.
// This is called by ealinit package.
func InitTscUnit() {
C.TscHz = C.rte_get_tsc_hz()
TscHz = uint64(C.TscHz)
TscGHz = float64(TscHz) / float64(time.Second)
TscSeconds = 1 / float64(TscHz)
TscNanos = 1 / TscGHz
C.TscGHz = C.double(TscGHz)
C.TscSeconds = C.double(TscSeconds)
C.TscNanos = C.double(TscNanos)
tsc1 := TscNow()
unixRef := time.Now()
tsc2 := TscNow()
C.TscTimeRefUnixNano_ = C.double(unixRef.UnixNano())
C.TscTimeRefTsc_ = (C.double(tsc1) + C.double(tsc2)) / 2.0
}
// TscTime represents a time point on TSC clock.
type TscTime uint64
// TscNow returns current TscTime.
func TscNow() TscTime {
return TscTime(C.rte_get_tsc_cycles())
}
// Add returns t+d.
func (t TscTime) Add(d time.Duration) TscTime {
return t + TscTime(ToTscDuration(d))
}
// Sub returns t-t0.
func (t TscTime) Sub(t0 TscTime) time.Duration {
return FromTscDuration(int64(t - t0))
}
// ToTime converts to time.Time.
func (t TscTime) ToTime() time.Time {
u := C.TscTime_ToUnixNano(C.TscTime(t))
return time.Unix(0, int64(u))
}
// FromTscDuration converts TSC duration to time.Duration.
func FromTscDuration(d int64) time.Duration {
return time.Duration(TscNanos * float64(d))
}
// ToTscDuration converts time.Duration to TSC duration.
func ToTscDuration(d time.Duration) int64 {
return int64(float64(d) / TscNanos)
}