github.com/robotn/xgb@v0.0.0-20190912153532-2cb92d044934/examples/atoms/main.go (about)

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"log"
     7  	"os"
     8  	"runtime"
     9  	"runtime/pprof"
    10  	"time"
    11  
    12  	"github.com/robotn/xgb"
    13  	"github.com/robotn/xgb/xproto"
    14  )
    15  
    16  var (
    17  	flagRequests    int
    18  	flagGOMAXPROCS  int
    19  	flagCpuProfName string
    20  	flagMemProfName string
    21  )
    22  
    23  func init() {
    24  	flag.IntVar(&flagRequests, "requests", 100000, "Number of atoms to intern.")
    25  	flag.IntVar(&flagGOMAXPROCS, "cpu", 1, "Value of GOMAXPROCS.")
    26  	flag.StringVar(&flagCpuProfName, "cpuprof", "cpu.prof",
    27  		"Name of CPU profile file.")
    28  	flag.StringVar(&flagMemProfName, "memprof", "mem.prof",
    29  		"Name of memory profile file.")
    30  
    31  	flag.Parse()
    32  
    33  	runtime.GOMAXPROCS(flagGOMAXPROCS)
    34  }
    35  
    36  func seqNames(n int) []string {
    37  	names := make([]string, n)
    38  	for i := range names {
    39  		names[i] = fmt.Sprintf("NAME%d", i)
    40  	}
    41  	return names
    42  }
    43  
    44  func main() {
    45  	X, err := xgb.NewConn()
    46  	if err != nil {
    47  		log.Fatal(err)
    48  	}
    49  
    50  	names := seqNames(flagRequests)
    51  
    52  	fcpu, err := os.Create(flagCpuProfName)
    53  	if err != nil {
    54  		log.Fatal(err)
    55  	}
    56  	defer fcpu.Close()
    57  	pprof.StartCPUProfile(fcpu)
    58  	defer pprof.StopCPUProfile()
    59  
    60  	start := time.Now()
    61  	cookies := make([]xproto.InternAtomCookie, flagRequests)
    62  	for i := 0; i < flagRequests; i++ {
    63  		cookies[i] = xproto.InternAtom(X,
    64  			false, uint16(len(names[i])), names[i])
    65  	}
    66  	for _, cookie := range cookies {
    67  		cookie.Reply()
    68  	}
    69  	fmt.Printf("Exec time: %s\n\n", time.Since(start))
    70  
    71  	fmem, err := os.Create(flagMemProfName)
    72  	if err != nil {
    73  		log.Fatal(err)
    74  	}
    75  	defer fmem.Close()
    76  	pprof.WriteHeapProfile(fmem)
    77  
    78  	memStats := &runtime.MemStats{}
    79  	runtime.ReadMemStats(memStats)
    80  
    81  	// This isn't right. I'm not sure what's wrong.
    82  	lastGcTime := time.Unix(int64(memStats.LastGC/1000000000),
    83  		int64(memStats.LastGC-memStats.LastGC/1000000000))
    84  
    85  	fmt.Printf("Alloc: %d\n", memStats.Alloc)
    86  	fmt.Printf("TotalAlloc: %d\n", memStats.TotalAlloc)
    87  	fmt.Printf("LastGC: %s\n", lastGcTime)
    88  	fmt.Printf("PauseTotalNs: %d\n", memStats.PauseTotalNs)
    89  	fmt.Printf("PauseNs: %d\n", memStats.PauseNs)
    90  	fmt.Printf("NumGC: %d\n", memStats.NumGC)
    91  }