获取Golang执行某个操作的进程时间

huangapple go评论81阅读模式
英文:

Golang get process time to an action

问题

我对完成这个动作需要花费多少时间非常感兴趣。有人有什么好的想法吗?或者有什么库可以使用?我用了一种简单的方法,但似乎是错误的方式。因为我在使用go时没有更多的经验。

以下是你的代码:

package main

import (
	"fmt"
	"time"
)

func main() {
	var d int = 0
	var beginTime = time.Now()
	for i := 0; i < 100000; i++ {

		for c := 0; c < 100; c++ {
			d = 1
		}
	}
	var endTime = time.Now()
	fmt.Println(beginTime, endTime)
	fmt.Println(time.Since(beginTime))
	fmt.Println(d)
}
英文:

I really interested in how much time is spending time to do this action. Does anybody have any best idea? or any library. I did with simple way, but it seems as wrong way. Because I did have more experience with workin on go

My have that code:

package main

import (
	&quot;fmt&quot;
	&quot;time&quot;
)

func main() {
	var d int = 0
	var beginTime = time.Now()
	for i := 0; i &lt; 100000; i++ {

		for c := 0; c &lt; 100; c++ {
			d = 1
		}
	}
	var endTime = time.Now()
	fmt.Println(beginTime, endTime)
	fmt.Println(time.Since(beginTime))
	fmt.Println(d)
}

答案1

得分: 1

使用内置的基准测试(Benchmarks)功能。

一个示例的基准测试函数如下所示:

func BenchmarkHello(b *testing.B) {
    for i := 0; i < b.N; i++ {
        fmt.Sprintf("hello")
    }
}

基准测试函数必须运行目标代码 b.N 次。在基准测试执行期间,b.N 的值会进行调整,直到基准测试函数的执行时间足够长,以便可靠地计时。输出结果

BenchmarkHello    10000000    282 ns/op

表示循环运行了 10000000 次,每次循环的速度为 282 纳秒。

编辑: 如果你想在运行时测量某个操作的时间,而不是在测试中,你的方法对我来说是可以的。

英文:

Use the built-in Benchmarks.

>A sample benchmark function looks like this:
>
func BenchmarkHello(b *testing.B) {
for i := 0; i < b.N; i++ {
fmt.Sprintf("hello")
}
}

>The benchmark function must run the target code b.N times. During benchark execution, b.N is adjusted until the benchmark function lasts long enough to be timed reliably. The output
>
BenchmarkHello 10000000 282 ns/op

>means that the loop ran 10000000 times at a speed of 282 ns per loop.

EDIT: If you want to measure time of doing something at runtime, and not in your tests, your way looks fine to me.

huangapple
  • 本文由 发表于 2015年5月7日 18:18:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/30098196.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定