| |
| |
| |
|
|
| package main |
|
|
| |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| import "C" |
|
|
| import ( |
| "fmt" |
| "runtime" |
| "runtime/debug" |
| "unsafe" |
| ) |
|
|
| const num = 100 |
|
|
| func init() { |
| register("CgoNoEscape", CgoNoEscape) |
| } |
|
|
| |
| func withNoEscape() { |
| var str string |
| C.runCWithNoEscape(unsafe.Pointer(&str)) |
| } |
|
|
| |
| func withoutNoEscape() { |
| var str string |
| C.runCWithoutNoEscape(unsafe.Pointer(&str)) |
| } |
|
|
| func CgoNoEscape() { |
| |
| debug.SetGCPercent(-1) |
|
|
| var stats runtime.MemStats |
| runtime.ReadMemStats(&stats) |
| preHeapObjects := stats.HeapObjects |
|
|
| for i := 0; i < num; i++ { |
| withNoEscape() |
| } |
|
|
| runtime.ReadMemStats(&stats) |
| nowHeapObjects := stats.HeapObjects |
|
|
| if nowHeapObjects-preHeapObjects >= num { |
| fmt.Printf("too many heap objects allocated, pre: %v, now: %v\n", preHeapObjects, nowHeapObjects) |
| } |
|
|
| runtime.ReadMemStats(&stats) |
| preHeapObjects = stats.HeapObjects |
|
|
| for i := 0; i < num; i++ { |
| withoutNoEscape() |
| } |
|
|
| runtime.ReadMemStats(&stats) |
| nowHeapObjects = stats.HeapObjects |
|
|
| if nowHeapObjects-preHeapObjects < num { |
| fmt.Printf("too few heap objects allocated, pre: %v, now: %v\n", preHeapObjects, nowHeapObjects) |
| } |
|
|
| fmt.Println("OK") |
| } |
|
|