performance - 如何测量golang中函数的执行时间,不包括等待时间

标签 performance go profile goroutine

我有一个需求来测量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/

相关文章:

c# - 带有帐户的新 Web 应用程序

javascript - 从编辑弹出窗口保存数据

uml - 什么是 UML 概要图以及何时使用它?

JavaScript 性能 : Modulus operation of negative Number within decrementing loop slowing the code by more than 100%

javascript - 如何从普通的 JavaScript 页面重定向到 Angular 6(微型网站到 Angular 6)?

mongodb - Golang Mongodb Bson字符串 slice 数组解码错误

json - Go中的排序接口(interface)

Mongodb 查询所有二级文档是否有任何子文档满足条件

SQL:存储是/否值的最佳方式?关注大型数据库中的性能

templates - 访问排序对列表的第一项