js计算耗时,可多次调用获取耗时

js计算耗时,可多次调用获取耗时

    let globalSinceTime = {}

    async function sinceTime(title = "默认标记") {
        try {
            let startTime = 0
            if (window && window.hasOwnProperty("performance")) {
                startTime = window.performance.now()
            } else {
                startTime = new Date().getTime()
            }
            globalSinceTime[title] = startTime
            return Promise.resolve(true)
        } catch (e) {
            return Promise.resolve(false)
        }
    }

    async function sinceTimeEnd(title = "默认标记") {
        try {
            let endTime = 0
            if (window && window.hasOwnProperty("performance")) {
                endTime = window.performance.now()
            } else {
                endTime = new Date().getTime()
            }
            let startTime = 0
            if (globalSinceTime.hasOwnProperty(title)) {
                startTime = globalSinceTime[title]
            }
            let since = endTime - startTime
            console.log(title + " 耗时:", since, "毫秒")
            return Promise.resolve(since)
        } catch (e) {
            return Promise.resolve(false)
        }
    }

使用

    sinceTime()
    console.time("耗时1")
    console.time("耗时2")
    setTimeout(() => {
        sinceTimeEnd()
        console.timeEnd("耗时1")
    }, 1000)
    setTimeout(() => {
        sinceTimeEnd()
        console.timeEnd("耗时2")
    }, 2000)

运行结果

默认标记 耗时: 1009.7999999970198 毫秒
耗时1: 1009.777099609375 ms
默认标记 耗时: 2011.4000000059605 毫秒
耗时2: 2011.431884765625 ms

 本文链接

 https://www.cnblogs.com/stumpx/p/16285700.html

 

posted @ 2022-05-18 17:55  stumpx  阅读(1271)  评论(0编辑  收藏  举报