英文:
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/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论