我有一个需求来测量go中插件的执行时间(cpu成本),我们可以将插件视为函数,可能有很多goroutine同时运行。更准确地说,执行时间应该不包括空闲时间(goroutine 等待时间),只有 cpu 获取时间(当前 goroutine 的)。 就像:
go func(){
// this func is a plugin
** start to record cpu acquire time of current func/plugin/goroutine **
** run code **
** stop to record cpu acquire time of current func/plugin/goroutine **
log.Debugf("This function is buzy for %d millisecs.", cpuAcquireTime)
** report cpuAcquirTime to monitor **
}()
在我的情况下,很难进行单元测试来衡量功能,代码很难解耦。
我搜索了google和stackoverflow,没有找到任何线索,有没有解决方案可以满足我的需求,是否占用太多资源?
最佳答案
Go 中没有内置方法来测量 CPU 时间,但您可以通过特定于平台的方式来实现。
例如,在 POSIX 系统(例如 Linux)上使用 clock_gettime
以 CLOCK_THREAD_CPUTIME_ID
作为参数。
同样,您可以使用 CLOCK_PROCESS_CPUTIME_ID
来测量进程 CPU 时间,并使用 CLOCK_MONOTONIC
来测量耗时。
示例:
package main
/*
#include <pthread.h>
#include <time.h>
#include <stdio.h>
static long long getThreadCpuTimeNs() {
struct timespec t;
if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t)) {
perror("clock_gettime");
return 0;
}
return t.tv_sec * 1000000000LL + t.tv_nsec;
}
*/
import "C"
import "fmt"
import "time"
func main() {
cputime1 := C.getThreadCpuTimeNs()
doWork()
cputime2 := C.getThreadCpuTimeNs()
fmt.Printf("CPU time = %d ns\n", (cputime2 - cputime1))
}
func doWork() {
x := 1
for i := 0; i < 100000000; i++ {
x *= 11111
}
time.Sleep(time.Second)
}
输出:
CPU time = 31250000 ns
请注意,输出以纳秒为单位。所以这里的CPU时间是0.03秒。
关于performance - 如何测量golang中函数的执行时间,不包括等待时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55990074/