Go编程语言 – 系统时间

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

Go Programming Language - System Time

问题

有人可以帮我回答如何在GO中获取系统时间吗?例如,在下面的代码中,我想知道第一个打印语句和第二个打印语句何时执行以及它们之间的时间差。

package main

import "fmt"

func main() {
    fmt.Println("Hello, 世界")
    fmt.Println("Hello, 世界")
}
英文:

Can anybody help me by answering how to get system time in GO. For example, in the below code, I want to know when the first print and second print statements are executed and what is the time difference between them.

package main

import "fmt"

func main() {
fmt.Println("Hello, 世界")
    fmt.Println("Hello, 世界")
}

答案1

得分: 5

请参考time包。文档可以在http://golang.org/pkg/time/找到。

要获取语句之前、第一个语句之后和最后一个语句之后的纳秒时间,并将它们打印出来:

package main

import "fmt"
import "time"

func main() {
  i1 := time.Now().UnixNano()
  fmt.Println("Hello, 世界")
  i2 := time.Now().UnixNano()
  fmt.Println("Hello, 世界")
  i3 := time.Now().UnixNano()
  fmt.Println("Check this out!")
  fmt.Println(i1)
  fmt.Println(i2)
  fmt.Println(i3)
  fmt.Println(time.Unix(0, i1).Format(time.StampNano))
  fmt.Println(time.Unix(0, i2).Format(time.StampNano))
  fmt.Println(time.Unix(0, i3).Format(time.StampNano))
}

在我的虚拟机中,我得到了以下结果:

~/dev/go/test $ nano test.go
~/dev/go/test $ go build test.go
~/dev/go/test $ ./test
Hello, 世界
Hello, 世界
Check this out!
1600000000000000000
1600000000000000000
1600000000000000000
Jan _2 15:04:05.000000000
Jan _2 15:04:05.000000000
Jan _2 15:04:05.000000000
英文:

See the time package. Documentation can be found at http://golang.org/pkg/time/

For getting the nanoseconds-time before, after the first and after the last of your statements, and then printing them out:

package main

import "fmt"
import "time"

func main() {
  i1 := time.Nanoseconds();
  fmt.Println("Hello, 世界")
  i2 := time.Nanoseconds();
  fmt.Println("Hello, 世界")
  i3 := time.Nanoseconds();
  fmt.Println("Check this out!")
  fmt.Println(i1)
  fmt.Println(i2)
  fmt.Println(i3)
  fmt.Println(time.NanosecondsToLocalTime(i1).Format(time.StampNano))
  fmt.Println(time.NanosecondsToLocalTime(i2).Format(time.StampNano))
  fmt.Println(time.NanosecondsToLocalTime(i3).Format(time.StampNano))
}

In my VM, I then get the following results:

~/dev/go/test $ nano test.go
~/dev/go/test $ 6g test.go; 
~/dev/go/test $ 6l test.6
~/dev/go/test $ ./6.out
Hello, 世界
Hello, 世界
Check this out!
1322386593830456000
1322386593830498000
1322386593830501000
Nov 27 10:36:33.830456000
Nov 27 10:36:33.830498000
Nov 27 10:36:33.830501000

答案2

得分: 1

查看time包。http://golang.org/pkg/time/

英文:

See the time package. http://golang.org/pkg/time/

huangapple
  • 本文由 发表于 2011年11月27日 02:33:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/8280619.html
匿名

发表评论

匿名网友

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

确定