Golang时间函数及测试函数执行时间案例

package main
import (
    "fmt"
    "time"
    
)


func main(){
    //【时间获取及格式化】
    //获取当前时间
    now_time := time.Now()
    fmt.Printf("Now_time=%v,数据类型:%T", now_time, now_time)


    //通过now获取年月日时分秒
    fmt.Printf("年=%v\n", now_time.Year())
    fmt.Printf("月=%v\n", now_time.Month())  //默认是英文的月份
    fmt.Printf("月=%v\n", int(now_time.Month()))  //加int转换为数字
    fmt.Printf("日=%v\n", now_time.Day())
    fmt.Printf("时=%v\n", now_time.Hour())
    fmt.Printf("分=%v\n", now_time.Minute())
    fmt.Printf("秒=%v\n", now_time.Second())



    //格式化日期时间①
    fmt.Printf("当前时间 %d-%d-%d %d:%d:%d \n", now_time.Year(), int(now_time.Month()), now_time.Day(), now_time.Hour(), now_time.Minute(), now_time.Second())

    //把格式化好的时间返回给一个变量,然后输出
    date_now := fmt.Sprintf("当前时间 %d-%d-%d %d:%d:%d \n", now_time.Year(), int(now_time.Month()), now_time.Day(), now_time.Hour(), now_time.Minute(), now_time.Second())
    fmt.Printf("date:%v\n", date_now)


    //格式化日期时间②
    //2006/01/02 15:04:05 这里必须数字一个不差的写
    //据说是因为golang设计者在这个时间有设计golang的想法
    fmt.Printf(now_time.Format("2006/01/02 15:04:05\n")) 
    fmt.Printf(now_time.Format("2006/01/02\n"))
    fmt.Printf(now_time.Format("15:04:05\n"))



    //【时间常量应用】
    //时间单位换算
    // const {
    //     Nanosecond Duration = 1 //纳秒
    //     Microsecond = 1000 * Nanosecond //微秒
    //     Millisecond = 1000 * Microsecond //毫秒
    //     Second = 1000 * Millisecond    ////     Minute = 60 * Second    //分钟
    //     Hour = 60 * Minute    //小时
    // }


    //每隔1秒输出一个数字,到100停止
    i := 0 
    for {
        i++
        fmt.Println(i)
        //休眠
        time.Sleep(time.Second)
        if i == 100 {
            break
        }
    }

    //每隔0.1秒输出一个数字,到100停止
    i := 0 
    for {
        i++
        fmt.Println(i)
        //休眠
        //这里不能用time.Second *0.1,会有异常
        time.Sleep(time.Millisecond * 100) 
        if i == 100 {
            break
        }
    }


    //获取当前时间戳还有纳秒时间戳,相当于php中的time和microtime
    fmt.Printf("unix时间戳=%v,unix纳秒时间戳=%v", now_time.Unix(), now_time.UnixNano())

}

 测试函数执行时间

package main
import (
    "fmt"
    "time"
    "strconv"
)

//测试函数
func test_func() {
    str := "" //声明一个字符串
    for i := 0; i < 100000; i++ {  //for循环10W次拼接
        str += "golang" + strconv.Itoa(i)  //整数转字符串拼接
    }
}

func main(){
    //测试test_func的执行时间
    start := time.Now().Unix()
    test_func()
    end := time.Now().Unix()
    fmt.Printf("执行消耗的时间为:%v秒", end - start)
}
D:\goproject\src\main>go run hello.go
执行消耗的时间为:10秒

 

posted @ 2018-08-21 13:03  温柔的风  阅读(4111)  评论(0编辑  收藏  举报