這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
Golang unsafe包使用筆記
unsafe包簡介
unsafe包提供了訪問底層記憶體的方法。是用unsafe函數可以提高訪問對象的速度。
應用情境
通常用於對大數組的遍曆。
訪問數組
package mainimport ( "fmt" "unsafe")func main() { array := []int{1, 2, 3} base := uintptr(unsafe.Pointer(&array[0])) size := unsafe.Sizeof(array[0]) ptr := unsafe.Pointer(base + 2*size) element := *(*int)(ptr) fmt.Println(element, array[2])}
訪問結構體
package mainimport ( "fmt" "unsafe")type Foo struct { A int B int}func main() { foo := &Foo{1, 2} fmt.Println(foo) base := uintptr(unsafe.Pointer(foo)) offset := unsafe.Offsetof(foo.A) ptr := unsafe.Pointer(base + offset) *(*int)(ptr) = 3 fmt.Println(foo)}
類型轉換
package mainimport ( "fmt" "unsafe")func main() { var f float64 = 0.0 var x uint64 = *(*uint64)(unsafe.Pointer(&f)) fmt.Println(f, x)}
注意事項
- unsafe可能引起相容性問題。
效能測試
代碼:
func sum(arr []int) int { sum := 0 for _, x := range arr { sum += x } return sum}func unsafeSum(arr []int) int { ptr := unsafe.Pointer(&arr[0]) count := len(arr) step := unsafe.Sizeof(arr[0]) sum := 0 for i := 0; i < count; i++ { sum += *(*int)(ptr) ptr = unsafe.Pointer(uintptr(ptr) + step) } return sum}func unsafeSum2(arr []int) int { base := unsafe.Pointer(&arr[0]) count := len(arr) step := unsafe.Sizeof(arr[0]) sum := 0 for i := 0; i < count; i++ { ptr := unsafe.Pointer(uintptr(base) + uintptr(i)*step) sum += *(*int)(ptr) } return sum}func unsafeSum3(arr []int) int { beg := unsafe.Pointer(&arr[0]) size := unsafe.Sizeof(arr[0]) end := unsafe.Pointer(uintptr(beg) + uintptr(len(arr))*size) ptr := beg sum := 0 for ptr != end { sum += *(*int)(ptr) ptr = unsafe.Pointer(uintptr(ptr) + size) } return sum}
測試代碼:
package mainimport ( "testing")var ( array = []int{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, })func BenchmarkUnsafeSum(b *testing.B) { for i := 0; i < b.N; i++ { unsafeSum(array) }}func BenchmarkSum(b *testing.B) { for i := 0; i < b.N; i++ { sum(array) }}func TestUnsafeSum(t *testing.T) { if result := unsafeSum(array); result != 550 { t.Fatal("expect %v get %v", 550, result) }}func TestUnsafeSum2(t *testing.T) { if result := unsafeSum2(array); result != 550 { t.Fatal("expect %v get %v", 550, result) }}func BenchmarkUnsafeSum2(b *testing.B) { for i := 0; i < b.N; i++ { unsafeSum2(array) }}func TestUnsafeSum3(t *testing.T) { if result := unsafeSum3(array); result != 550 { t.Fatal("expect %v get %v", 550, result) }}func BenchmarkUnsafeSum3(b *testing.B) { for i := 0; i < b.N; i++ { unsafeSum3(array) }}
結果:
BenchmarkUnsafeSum-2 20000000 94.0 ns/opBenchmarkSum-2 10000000 129 ns/opBenchmarkUnsafeSum2-2 10000000 126 ns/opBenchmarkUnsafeSum3-2 20000000 84.0 ns/opPASSok tq/lab/Unsafe 6.926s
參考資料
- http://golang.org/pkg/unsafe
歷程記錄
- 2017年06月15日 建立文檔。