Equivalent of python time.time()-started in golang

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

Equivalent of python time.time()-started in golang

问题

在Go语言中,你可以使用time包来实现类似的功能。下面是一个示例代码:

package main

import (
	"fmt"
	"time"
)

func main() {
	started := time.Now()
	doProcess()
	elapsed := time.Since(started)
	fmt.Println(elapsed.Seconds())
}

func doProcess() {
	// 执行你的具体操作
}

在这个示例中,我们使用time.Now()函数获取开始时间,执行doProcess()函数,然后使用time.Since()函数计算经过的时间。最后,我们使用elapsed.Seconds()方法获取经过的秒数并打印出来。

英文:

In python I can see how many seconds have elapsed during a specific process like,

started = time.time()
doProcess()
print(time.time()-started)

Whats the equivelent in golang?

答案1

得分: 2

import (
    "fmt"
    "time"
)

func main() {
    started := time.Now()
    doProcess()
    fmt.Println(time.Now().Sub(started).Seconds())
}
import (
    "fmt"
    "time"
)

func main() {
    started := time.Now()
    doProcess()
    fmt.Println(time.Now().Sub(started).Seconds())
}
英文:
import (
    "fmt"
    "time"
)

func main() {
    started := time.Now()
    doProcess()
    fmt.Println(time.Now().Sub(started).Seconds())
}

答案2

得分: 2

import (
    "fmt"
    "time"
)

func main() {
    begin := time.Now()
    time.Sleep(10 * time.Millisecond)
    end := time.Now()

    duration := end.Sub(begin)

    fmt.Println(duration)

}
import (
    "fmt"
    "time"
)

func main() {
    begin := time.Now()
    time.Sleep(10 * time.Millisecond)
    end := time.Now()

    duration := end.Sub(begin)

    fmt.Println(duration)

}
英文:
import (
	"fmt"
	"time"
)

func main() {
	begin := time.Now()
  	time.Sleep(10 * time.Millisecond)
  	end := time.Now()

  	duration := end.Sub(begin)
	
	fmt.Println(duration)

}

答案3

得分: 1

以下是翻译好的内容:

时间包

func Since

func Since(t Time) Duration

Since 返回自 t 以来经过的时间。它是 time.Now().Sub(t) 的简写形式。

你的 Go 语言中的 Python 示例:

package main

import (
	"fmt"
	"time"
)

func main() {
	started := time.Now()
	time.Sleep(1 * time.Second)
	fmt.Println(time.Since(started))
}

输出:

1s
英文:

> Package time
>
> func Since
>
> func Since(t Time) Duration
>
> Since returns the time elapsed since t. It is shorthand for
> time.Now().Sub(t).

Your Python example in Go:

package main

import (
	"fmt"
	"time"
)

func main() {
	started := time.Now()
	time.Sleep(1 * time.Second)
	fmt.Println(time.Since(started))
}

Output:

1s

huangapple
  • 本文由 发表于 2017年5月13日 21:01:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/43953459.html
匿名

发表评论

匿名网友

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

确定