dsvyc66464 2019-05-05 08:16
浏览 392

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

I have a demand to measure execute time(cpu cost) of plugins in go, we can treat plugins as functions, there may be many goroutine running in the same time. More precisely, the execute time should exclude idle time(goroutine waiting time), only cpu acquire time(of current goroutine). it's like:

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 **
}()

In my circunstance, it's hard to make unit test to measure function, the code is hard to decouple.

I search google and stackoverflow and find no clue, is there any solution to satisfy my demand, and does it take too much resource?

  • 写回答

1条回答 默认 最新

  • doushang4293 2019-05-08 09:42
    关注

    There is no built-in way in Go to measure CPU time, but you can do it in a platform-specific way.

    For example, on POSIX systems (e.g. Linux) use clock_gettime with CLOCK_THREAD_CPUTIME_ID as the parameter.

    Similarly you can use CLOCK_PROCESS_CPUTIME_ID to measure process CPU time and CLOCK_MONOTONIC for elapsed time.

    Example:

    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
    ", (cputime2 - cputime1))
    }
    
    func doWork() {
        x := 1
        for i := 0; i < 100000000; i++ {
            x *= 11111
        }
        time.Sleep(time.Second)
    }
    

    Output:

    CPU time = 31250000 ns
    

    Note the output is in nanoseconds. So here CPU time is 0.03 sec.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据