Huskar
Huskar

Reputation: 61

How to measure execution time of function in golang, excluding waiting time

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?

Upvotes: 2

Views: 4832

Answers (2)

Brent
Brent

Reputation: 43

For people who stumble on this later like I did, you can actually use the built-in syscall.Getrusage instead of using Cgo. An example of this looks like

func GetCPU() int64 {
    usage := new(syscall.Rusage)
    syscall.Getrusage(syscall.RUSAGE_SELF, usage)
    return usage.Utime.Nano() + usage.Stime.Nano()
}

where I have added up the Utime (user CPU time) and Stime (system CPU time) of the calling process (RUSAGE_SELF) after converting them both to nanoseconds. man 2 getrusage has a bit more information on this system call.

The documentation for syscall.Timeval suggests that Nano() returns the time in nanoseconds since the Unix epoch, but in my tests and looking at the implementation it appears actually to return just the CPU time in nanoseconds, not in nanoseconds since the Unix epoch.

Upvotes: 2

rustyx
rustyx

Reputation: 85491

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\n", (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.

Upvotes: 1

Related Questions