英文:
golang code insert/substitute
问题
我喜欢不让代码重复。但是我有一个情况,当我想要测量执行时间时,我必须在每个函数中重复这个操作,而且我对此无能为力。
例如,一个函数:
func someFunc() {
start_time := time.Now()
defer fmt.Println("Execution time: %v", time.Now().Sub(start_time))
// ... 做一些业务 ...
}
现在我必须在每个函数中重复这两行代码(原始代码中由于调用函数名的原因更加复杂)。所以我无法创建一个测量时间的函数,因为我必须在其中使用defer
。我甚至不能为第二行代码创建一个函数,因为在原始代码中它在Println
中调用了一个函数名,所以结果的名称将不是所需的函数。
是否有任何方法可以通过某个标签或模板插入这段代码,例如:
func someFunc() {
//go-insert measuretime.tmpl
// ... 做一些业务 ...
}
而measuretime.tmpl
的内容是:
start_time := time.Now()
defer fmt.Println("Execution time: %v", time.Now().Sub(start_time))
英文:
I like not to allow the code to repeat. But I have a situation, when I must repeat it in every function I want to measure execution time, and I can do nothing to it.
For example, a function:
func someFunc() {
start_time := time.Now()
defer fmt.Println("Execution time: %v", time.Now().Sub(start_time))
<... doing some bussiness ...>
}
Now I must repeat this two first strokes in every function (and in original they are more complicated because of calling a function name). So I cannot make a function which measures time, because i must use defer inside of it. I cannot make a function even for second stroke, cause in original it calls a function name in Println and that's why the resulting name will not be of needed function.
Is there any way to insert this code by some label or a template, for example, like this:
func someFunc() {
//go-insert measuretime.tmpl
<... doing some bussiness ...>
}
And measuretime.tmpl is:
start_time := time.Now()
defer fmt.Println("Execution time: %v", time.Now().Sub(start_time))
答案1
得分: 1
这个技巧可能会有所帮助:延迟调用一个返回包含起始时间的函数。
func elapsed() func() {
start := time.Now()
return func() {
fmt.Println("Duration was", time.Since(start))
}
}
调用方式如下:
defer elapsed()()
话虽如此,在Go语言中,通常使用基准测试来衡量性能。请参阅如何编写Go语言基准测试。
英文:
This trick might help: defer a call to a function returning a function enclosing the start time.
func elapsed() func() {
start := time.Now()
return func() {
fmt.Println("Duration was", time.Since(start))
}
}
Call it as follows:
defer elapsed()()
Having said that, benchmarking is the usual way to measure performance in Go. See how to write benchmarks in Go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论