英文:
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 (
"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)
}
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论