Use golang to achieve python's timer

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

Use golang to achieve python's timer

问题

Python:

with Timer() as t:
    # TODO a lot

print "scan all disks, cost: %s secs" % t.secs

现在,如何使用 golang 实现这个功能?

我已经在谷歌上搜索了,但是没有找到我想要的答案。

为什么我在这里发布问题然后被踩票?

谢谢你的帮助!

英文:

Python:

with Timer() as t :
          // TODO a lot

print "scan all disks,cost:%s secs" % t.secs

Now,how to use golang to achieve this?

I had google this but I can not find any answers I want.

Why am I post my questions in here and then got downvote?

Thank you your help!!!

答案1

得分: 4

你可以编写一个函数,接受一个函数作为参数,运行它并打印时间:

import (
  "time"
  "fmt"
)

func TimeIt(f func(), description string) {
   start := time.Now()
   f()
   fmt.Printf("运行 %s 花费了 %v\n", description, time.Since(start))
}

然后可以这样触发它:

func main() {
    TimeIt(doSomething, "做某事")
}

或者将其作为闭包直接应用于代码片段:

TimeIt(func() {
     do()
     some()
     stuff()
   },
   "任何事情")
英文:

You can write a function that accepts a function, runs it and prints the time:

import (
  "time"
  "fmt"
)

func TimeIt(f func(), description string) {
   start := time.Now()
   f()
   fmt.Printf("Running %s took %v\n", description, time.Since(start))
}

And then trigger it like so:

func main() {
    TimeIt(doSomething, "Doing something")
}

Or just sprinkle it on pieces of code as a closure:

TimeIt(func() {
     do()
     some()
     stuff()
   },
   "whatever")

答案2

得分: 3

在Go语言中,另一种方法是定义一个计时器函数,并使用defer语句在函数返回时调用它。

package main

import (
	"fmt"
	"time"
)

func timer(start time.Time, description string) {
	fmt.Printf("%s 耗时 %s\n", description, time.Since(start))
}

func main() {
	func() {
		defer timer(time.Now(), "扫描所有磁盘")
		// TODO: 很多操作
	}()
	// 输出: 扫描所有磁盘 耗时 0s
}

你可以通过将特定命令包装到一个匿名函数中(参见上面的示例)来测量其执行时间,或者通过在函数顶部简单地放置defer语句来测量函数的执行时间,例如:

func foo() {
	defer timer(time.Now(), "foo")
	// ...
}
// 输出: foo 耗时 0s
英文:

Another way to do this in go is to define a timer function and use the defer statement to call it when the function returns.

package main

import (
    "fmt"
    "time"
)

func timer(start time.Time, description string) {
    fmt.Printf("%s took %s\n", description, time.Since(start))
}


func main() {
    func() {
		defer timer(time.Now(), "scan all disks")
	    // TODO: alot
    }()
    // OUTPUT: scan all disks took 0s
}

You can measure the time of specific commands by wrapping them into an anonymous function (see above) or you measure the time of a function by simply putting the defer statement at its top, e.g.

func foo() {
    defer timer(time.Now(), "foo")
    // ...
}
// OUTPUT: foo took 0s

huangapple
  • 本文由 发表于 2017年6月20日 16:01:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/44647225.html
匿名

发表评论

匿名网友

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

确定