首页 技术 正文
技术 2022年11月21日
0 收藏 589 点赞 3,958 浏览 1504 个字

当时候需要去计算一段代码或一个程序所消耗时间的时候,就需要进行统计时间,用程序去计算某一段代码的执行所需要的时间远比用眼睛直接去看程序运行时间高很多。

go语言中的time包中提供了函数来提供计算消耗时间,具体的使用方式如下案例所示:

bT := time.Now()            // 开始时间

eT := time.Since(bT)      // 从开始到当前所消耗的时间

fmt.Println(“Run time: “, eT)

1.朴素方法

在函数起始位置计算当前时间,在函数结束位置算出耗时。

package mainimport (
"fmt"
"time"
)func sum(n int) int {
startT := time.Now()//计算当前时间 total := 0
for i:=1; i <= n; i++ {
total += i
}tc := time.Since(startT)//计算耗时
fmt.Printf("time cost = %v\n", tc)
return total
}func main() {
count := sum(100)
fmt.Printf("count = %v\n", count)
}

编译运行输出:

time cost = 350ns
count = 5050

2.简洁方法

计算当前时间与计算耗时放在两处,难免显得丑陋,且不易阅读。如果有多个函数需要统计耗时,那么多处书写重复的两行代码会造成代码冗余。由于 Golang 提供了函数延时执行的功能,借助 defer ,我们可以通过函数封装的方式来避免代码冗余。

package mainimport (
"fmt"
"time"
)//@brief:耗时统计函数
func timeCost(start time.Time){
tc:=time.Since(start)
fmt.Printf("time cost = %v\n", tc)
}func sum(n int) int {
defer timeCost(time.Now())
total := 0
for i:=1; i <= n; i++ {
total += i
} return total
}func main() {
count := sum(100)
fmt.Printf("count = %v\n", count)
}

编译运行输出:

time cost = 1.574µs
count = 5050

通过输出可以看到sum()耗时增加了,因为增加了一次timeCost()函数调用。不过相比于函数封装带来的便利与代码美观,新增的耗时是微不足道可以接受的。

3.优雅方法

每次调用耗时统计函数timeCost()都需要传入time.Now(),重复书写time.Now()无疑造成了代码冗余。我们在上面的基础上,进行进一步的封装,实现如下。

package mainimport (
"fmt"
"time"
)//@brief:耗时统计函数
func timeCost() func() {
start := time.Now()
return func() {
tc:=time.Since(start)
fmt.Printf("time cost = %v\n", tc)
}
}func sum(n int) int {
defer timeCost()()//注意,是对 timeCost()返回的函数进行调用,因此需要加两对小括号
total := 0
for i:=1; i <= n; i++ {
total += i
} return total
}func main() {
count := sum(100)
fmt.Printf("count = %v\n", count)
}

编译运行输出:

time cost = 1.204µs
count = 5050转:https://cloud.tencent.com/developer/article/1447903
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,077
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,552
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,400
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,813
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,895