forked from smallnest/epoller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fd_test.go
55 lines (48 loc) · 1.02 KB
/
fd_test.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
package epoller
import (
"net"
"reflect"
"runtime"
"syscall"
"testing"
)
func reflectSocketFDAsUint(conn net.Conn) uint64 {
tcpConn := reflect.Indirect(reflect.ValueOf(conn)).FieldByName("conn")
fdVal := tcpConn.FieldByName("fd")
pfdVal := reflect.Indirect(fdVal).FieldByName("pfd")
return pfdVal.FieldByName("Sysfd").Uint()
}
func rawSocketFD(conn net.Conn) uint64 {
if con, ok := conn.(syscall.Conn); ok {
raw, err := con.SyscallConn()
if err != nil {
return 0
}
sfd := uint64(0)
raw.Control(func(fd uintptr) {
sfd = uint64(fd)
})
return sfd
}
return 0
}
func BenchmarkSocketFdReflect(b *testing.B) {
var con, _ = net.Dial(`udp`, "8.8.8.8:53")
fd := uint64(0)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
fd = reflectSocketFDAsUint(con)
}
runtime.KeepAlive(fd)
}
func BenchmarkSocketFdRaw(b *testing.B) {
con, _ := net.Dial(`udp`, "8.8.8.8:53")
fd := uint64(0)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
fd = rawSocketFD(con)
}
runtime.KeepAlive(fd)
}