Test Memory on go

前端之家收集整理的这篇文章主要介绍了Test Memory on go前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1.  
  1.  
  1. package main
  1.  
  1. import (
  1. "container/list"
  1. "fmt"
  1. "net/http"
  1. "os"
  1. "runtime"
  1. "strconv"
  1. // "strings"
  1. "io"
  1. "log"
  1. "sync"
  1. "syscall"
  1. "time"
  1. )
  1.  
  1. var lockger sync.Mutex
  1. var fansMap map[int]*list.List
  1.  
  1. func root(w http.ResponseWriter, r *http.Request) {
  1. fmt.Fprintf(w, "<h1>Hello %s!</h1>", r.URL.Path[1:])
  1. url := "get?key=123"
  1. fmt.Fprintf(w, "<a href=%s>%s</a><br />", url, url)
  1. url = "set?key=123&v=100"
  1. fmt.Fprintf(w, url)
  1. url = "stop"
  1. fmt.Fprintf(w, url)
  1. }
  1. func setData(w http.ResponseWriter, "...")
  1. runtime.GC()
  1. }
  1. func getData(w http.ResponseWriter, r *http.Request) {
  1. key := r.FormValue("key")
  1. i, _ := strconv.Atoi(key)
  1. fmt.Fprintf(w, "val:%d", i)
  1. lockger.Lock()
  1. l, ok := fansMap[i]
  1. lockger.Unlock()
  1. if ok {
  1. fmt.Fprintf(w, "mapok\n")
  1. for e := l.Front(); e != nil; e = e.Next() {
  1. // do something with l.Value
  1. v := e.Value.(int)
  1. fmt.Fprintf(w, "%d,", v)
  1. }
  1. }
  1. //r.ParseForm()
  1. //for k, v := range r.Form {
  1. // fmt.Fprintf(w, "key:%s", k)
  1. // fmt.Fprintf(w, "val:%d", v)
  1. // //i, _ := strconv.Atoi(v)
  1. //}
  1. }
  1.  
  1. // getEnv Request Handler
  1. func getEnv(writer http.ResponseWriter, req *http.Request) {
  1. env := os.Environ()
  1. writer.Write([]byte("<h1>??????</h1><br>"))
  1. for _, v := range env {
  1. writer.Write([]byte(v + "<br>"))
  1. }
  1. writer.Write([]byte("<br>"))
  1. }
  1. func StopServer(w http.ResponseWriter, req *http.Request) {
  1. responseString := "STOP"
  1. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  1. w.Header().Set("Content-Length", strconv.Itoa(len(responseString)))
  1. io.WriteString(w, responseString)
  1. f, canFlush := w.(http.Flusher)
  1. if canFlush {
  1. f.Flush()
  1. }
  1. conn, _, err := w.(http.Hijacker).Hijack()
  1. if err != nil {
  1. log.Fatalf("error while shutting down: %v", err)
  1. }
  1. conn.Close()
  1. log.Println("Shutting down")
  1. os.Exit(0)
  1. }
  1. func main() {
  1. np := runtime.Numcpu()
  1. runtime.GOMAXPROCS(np - 1)
  1. println(np)
  1.  
  1. go ReportStatus()
  1. fansMap = make(map[int]*list.List)
  1. t := time.Now()
  1. var i int
  1. var fans *list.List
  1. max := 1000000
  1. for i = 0; i < max; i++ {
  1. fans = list.New()
  1. fansMap[i] = fans
  1. for j := 1; j <= 200; j++ {
  1. _ = fans.PushFront(j)
  1. }
  1. fans.PushFront(i)
  1.  
  1. if i%1000 == 0 {
  1. fmt.Println("i=", i)
  1. }
  1.  
  1. memstatus := MemStat()
  1. if memstatus.Free < 512000000 {
  1. fmt.Println("OUT OF MEMORY")
  1. break
  1. }
  1. }
  1.  
  1. fmt.Println("list: " + time.Now().Sub(t).String())
  1. http.HandleFunc("/", root)
  1. http.HandleFunc("/get", getData)
  1. http.HandleFunc("/set", setData)
  1. http.HandleFunc("/stop", StopServer)
  1. http.HandleFunc("/env", getEnv)
  1. http.ListenAndServe(":8080", nil)
  1. }
  1.  
  1. type MemStatus struct {
  1. All uint32 `json:"all"`
  1. Used uint32 `json:"used"`
  1. Free uint32 `json:"free"`
  1. Self uint64 `json:"self"`
  1. }
  1.  
  1. func MemStat() MemStatus {
  1. //自身占用
  1. memStat := new(runtime.MemStats)
  1. runtime.ReadMemStats(memStat)
  1. mem := MemStatus{}
  1. mem.Self = memStat.Alloc
  1.  
  1. //系统占用,仅linux/mac下有效
  1. //system memory usage
  1. sysInfo := new(syscall.Sysinfo_t)
  1. err := syscall.Sysinfo(sysInfo)
  1. if err == nil {
  1. mem.All = sysInfo.Totalram * uint32(syscall.Getpagesize())
  1. mem.Free = sysInfo.Freeram * uint32(syscall.Getpagesize())
  1. mem.Used = mem.All - mem.Free
  1. }
  1. return mem
  1. }
  1. func ReportStatus() {
  1. memStats := &runtime.MemStats{}
  1. runtime.ReadMemStats(memStats)
  1. nsInMs := float64(time.Millisecond)
  1. prefix := "MT"
  1. for {
  1. //now := time.Now()
  1. fmt.Println("=========")
  1.  
  1. fmt.Println(fmt.Sprintf("%s.goroutines", prefix),
  1. float64(runtime.NumGoroutine()))
  1. fmt.Println(fmt.Sprintf("%s.memory.allocated",
  1. float64(memStats.Alloc))
  1. fmt.Println(fmt.Sprintf("%s.memory.mallocs",
  1. float64(memStats.Mallocs))
  1. fmt.Println(fmt.Sprintf("%s.memory.frees",
  1. float64(memStats.Frees))
  1. fmt.Println(fmt.Sprintf("%s.memory.gc.total_pause",
  1. float64(memStats.PauseTotalNs)/nsInMs)
  1. fmt.Println(fmt.Sprintf("%s.memory.heap",
  1. float64(memStats.HeapAlloc))
  1. fmt.Println(fmt.Sprintf("%s.memory.stack",
  1. float64(memStats.StackInuse))
  1. time.Sleep(10e8)
  1. }
  1.  
  1. }
  1.  
  1. //func reportRuntimeStats(prefix, context string,
  1. // dimensions Dimensions, sleep time.Duration) {
  1.  
  1. // memStats := &runtime.MemStats{}
  1. // lastSampleTime := time.Now()
  1. // var lastPauseNs uint64 = 0
  1. // var lastNumGc uint32 = 0
  1.  
  1. // nsInMs := float64(time.Millisecond)
  1.  
  1. // for self.runtimeStatsRunning {
  1. // runtime.ReadMemStats(memStats)
  1.  
  1. // now := time.Now()
  1.  
  1. // Println(fmt.Sprintf("%s.goroutines", prefix),
  1. // float64(runtime.NumGoroutine()), now, context, dimensions)
  1. // Println(fmt.Sprintf("%s.memory.allocated",
  1. // float64(memStats.Alloc), dimensions)
  1. // Println(fmt.Sprintf("%s.memory.mallocs",
  1. // float64(memStats.Mallocs), dimensions)
  1. // Println(fmt.Sprintf("%s.memory.frees",
  1. // float64(memStats.Frees), dimensions)
  1. // Println(fmt.Sprintf("%s.memory.gc.total_pause",
  1. // float64(memStats.PauseTotalNs)/nsInMs, dimensions)
  1. // Println(fmt.Sprintf("%s.memory.heap",
  1. // float64(memStats.HeapAlloc), dimensions)
  1. // Println(fmt.Sprintf("%s.memory.stack",
  1. // float64(memStats.StackInuse), dimensions)
  1.  
  1. // if lastPauseNs > 0 {
  1. // pauseSinceLastSample := memStats.PauseTotalNs - lastPauseNs
  1. // Println(fmt.Sprintf("%s.memory.gc.pause_per_second",
  1. // float64(pauseSinceLastSample)/nsInMs/sleep.Seconds(), dimensions)
  1. // }
  1. // lastPauseNs = memStats.PauseTotalNs
  1.  
  1. // countGc := int(memStats.NumGC - lastNumGc)
  1. // if lastNumGc > 0 {
  1. // diff := float64(countGc)
  1. // diffTime := now.Sub(lastSampleTime).Seconds()
  1. // Println(fmt.Sprintf("%s.memory.gc.gc_per_second",
  1. // diff/diffTime, dimensions)
  1. // }
  1.  
  1. // // get the individual pause times
  1. // if countGc > 0 {
  1. // if countGc > 256 {
  1. // fmt.Fprintf(os.Stderr, "We're missing some gc pause times")
  1. // countGc = 256
  1. // }
  1.  
  1. // for i := 0; i < countGc; i++ {
  1. // idx := int((memStats.NumGC-uint32(i))+255) % 256
  1. // pause := float64(memStats.PauseNs[idx])
  1. // self.Aggregate(fmt.Sprintf("%s.memory.gc.pause",
  1. // pause/nsInMs, dimensions)
  1. // }
  1. // }
  1.  
  1. // // keep track of the prevIoUs state
  1. // lastNumGc = memStats.NumGC
  1. // lastSampleTime = now
  1.  
  1. // time.Sleep(sleep)
  1. // }
  1. //}

猜你在找的Go相关文章