@mSolo
2015-05-07T09:05:21.000000Z
字数 3479
阅读 1514
Go
Golang
where := func() {
_, file, line, _ := runtime.Caller(1)
log.Printf(“%s:%d”, file, line)
}
runtime.GC()
fmt.Printf(“%d\n”, runtime.MemStats.Alloc/1024)
runtime.SetFinalizer(obj, func(obj *typeObj))
package main
import (
“fmt”
“./even/even”
)
func main() {
for i:=0; i<=100; i++ {
fmt.Printf(“Is the integer %d even? %v\n”, i, even.Even(i))
}
}
package even
func Even(i int) bool { // Exported functions
return i%2 == 0
}
func Odd(i int) bool {
return i%2 != 0
}
package even
import “testing”
func TestEven(t *testing.T) {
if !Even(10) {
t.Log(“10 must be even!”)
t.Fail()
}
if Even(7) {
t.Log(“7 is not even!”)
t.Fail()
}
}
func TestOdd(t *testing.T) {
if !Odd(11) {
t.Log(“11 must be odd!”)
t.Fail()
}
if Odd(10) {
t.Log(“10 is not odd!”)
t.Fail()
}
}
var tests = []struct{ // Test table
in string
out string
}{
{“in1”, “exp1”},
{“in2”, “exp2”},
// ...
}
func TestFunction(t *testing.T) {
for i, tt := range tests {
s := FuncToBeTested(tt.in)
verify(t, i, “FuncToBeTested: “, tt.in, s, tt.out)
}
}
func verify(t *testing.T, testnum int, testcase, input, output, expected string) {
if expected != output {
t.Errorf(“%d. %s with input = %s: output %s != %s”,
testnum, testcase, input, output, expected)
}
}
go test –x –v –cpuprofile=cpuprof.out –file x_test.go
go test –x –v –memprofile=memprof.out –file x_test.go
var cpuprofile = flag.String(“cpuprofile”, “”, “write cpu profile to file”)
func main() {
flag.Parse()
if *cpuprofile != “” {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
...
progexec -cpuprofile=progexec.prof
gopprof progexec progexec.prof
If it is seen that the function runtime.mallocgc (which both allocates and runs periodic garbage collections) is heavily used, then it is time for memory profiling.
var memprofile = flag.String(“memprofile”, “”, “write memory profile to this file”)
// ...
CallToFunctionWhichAllocatesLotsOfMemory()
if *memprofile != “” {
f, err := os.Create(*memprofile)
if err != nil {
log.Fatal(err)
}
pprof.WriteHeapProfile(f)
f.Close()
return
}
progexec -memprofile=progexec.mprof
gopprof progexec progexec.mprof
gopprof --inuse_objects progexec progexec.mprof
import _ “http/pprof”
gopprof http://localhost:6060/debug/pprof/profile # 30-second CPU profile
gopprof http://localhost:6060/debug/pprof/heap # heap profile
$ go build -x crypto/hmac
WORK=/tmp/go-build249279931
mkdir -p $WORK/crypto/hmac/_obj/
mkdir -p $WORK/crypto/
$ cd /home/dfc/go/src/pkg/crypto/hmac
$ /home/dfc/go/pkg/tool/linux_arm/5g -o $WORK/crypto/hmac/_obj/_go_.5 -p crypto/hmac -complete -D _/home/dfc/go/src/pkg/crypto/hmac -I $WORK ./hmac.go
$ /home/dfc/go/pkg/tool/linux_arm/pack grcP $WORK $WORK/crypto/hmac.a $WORK/crypto/hmac/_obj/_go_.5
$ go install –x crypto/hmac
# ...
$ mkdir -p /home/dfc/go/pkg/linux_arm/crypto/
$ cp $WORK/crypto/hmac.a /home/dfc/go/pkg/linux_arm/crypto/hmac.a