Go 版快速入门

在 Go 中,profiler_quickstart 示例针对 Cloud Profiler 模拟 CPU 密集型工作负载。

代码示例

Go

如需了解详情,请参阅性能分析器 Go API 参考文档

如需向 Profiler 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


// Sample profiler_quickstart simulates a CPU-intensive workload for profiler.
package main

import (
	"log"
	"runtime"

	"cloud.google.com/go/profiler"
)

func busyloop() {
	for {
		load()
		// Make sure to yield so that the profiler thread
		// gets some CPU time even on single core machines
		// where GOMAXPROCS is 1. Not needed in real programs
		// as typically the preemption happens naturally.
		runtime.Gosched()
	}
}

func load() {
	for i := 0; i < (1 << 20); i++ {
	}
}

func main() {
	err := profiler.Start(profiler.Config{
		Service:              "hello-profiler",
		NoHeapProfiling:      true,
		NoAllocProfiling:     true,
		NoGoroutineProfiling: true,
		DebugLogging:         true,
		// ProjectID must be set if not running on GCP.
		// ProjectID: "my-project",
	})
	if err != nil {
		log.Fatalf("failed to start the profiler: %v", err)
	}
	busyloop()
}

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器