前端 performance api使用 —— mark、measure计算vue3页面echarts渲染时间


yma16-logo

⭐前言

大家好,我是yma16,本文分享关于 前端 performance api使用 —— mark、measure计算vue3页面echarts渲染时间。
Performance API

浏览器的Performance API 是一组用于测量和监视网页性能的接口。它提供了一些方法和事件,可以用于收集和分析页面的性能数据。

💖vue3系列文章

vue3 + fastapi 实现选择目录所有文件自定义上传到服务器
前端vue2、vue3去掉url路由“ # ”号——nginx配置
csdn新星计划vue3+ts+antd赛道——利用inscode搭建vue3(ts)+antd前端模板
认识vite_vue3 初始化项目到打包
python_selenuim获取csdn新星赛道选手所在城市用echarts地图显示
让大模型分析csdn文章质量 —— 提取csdn博客评论在文心一言分析评论区内容
前端vue3——html2canvas给网站截图生成宣传海报
vue3+echarts可视化——记录我的2023编程之旅
前端vite+vue3——自动化配置路由布局
前端vite+vue3——可视化页面性能耗时指标(fmp、fp)
前端vite+rollup前端监控初始化——封装基础fmp消耗时间的npm包并且发布npm beta版本

⭐Performance api计算持续时间

计算单位:毫秒,使用performance.now()为参考。
performance.now用于精确测量代码执行时间的高精度时钟。该方法返回从性能开始计算的时间戳,以毫秒为单位。

💖 mark用法

mark() 方法在浏览器的性能缓冲区中使用给定名称添加一个timestamp(时间戳) 。

应用定义的时间戳可以通过 Performance 接口的一个 getEntries*() 方法 (getEntries(), getEntriesByName() 或者 getEntriesByType()) 检索到。

标记 的 performance entry将具有以下属性值:

  • entryType - 设置为 “mark”.
  • name - 设置为 mark 被创建时给出的 “name”。
  • startTime - 设置为 mark() 方法被调用时的 timestamp 。
  • duration - 设置为 “0” (标记没有持续时间).

如果这个方法被指定的 name 已经存在于PerformanceTiming 接口,会抛出一个SyntaxError错误。

用法

performance.mark(name,{detail:detailOption});

示例

// 创建一些标记。
performance.mark("start");
performance.mark("end");
performance.mark("monkey");
performance.mark("monkey");
performance.mark("dog");
performance.mark("dog");

// 获取所有的 PerformanceMark 条目。
const allEntries = performance.getEntriesByType("mark");
console.log(allEntries.length);
// 6

// 获取所有的 "monkey" PerformanceMark 条目。
const monkeyEntries = performance.getEntriesByName("monkey");
console.log(monkeyEntries.length);
// 2

定义detailOption配置项

performance.mark('csdn-page',{detail:{user:'yma16'}})
const monkeyEntries = performance.getEntriesByName("csdn-page");
console.log(monkeyEntries);

运行结果:

[
	{
		"detail":{
    		"user": "yma16"
		},
	    "name": "csdn-page",
	    "entryType": "mark",
	    "startTime": 1506139.5,
	    "duration": 0
	}
]

💖 measure用法

measure() 方法在浏览器性能记录缓存中创建了一个名为时间戳的记录来记录两个特殊标志位(通常称为开始标志和结束标志)。被命名的时间戳称为一次测量(measure)。

前提是存在mark标记的startMark和endMark
语法如下

performance.measure(name, startMark, endMark);

自定义开始结束的用法
自定义detail对象,start的开始时间,end的结束时间,得到end-start的duration

performance.measure(name, {
  detail: detailOptions,
  start: startTime,
  end: endTime,
});

常规用法示例示例

performance.mark('test-start')
performance.mark('test-end')
performance.measure('test-duration','test-start','test-end')

得到结果

{
	"detail":null,
    "name": "test-duration",
    "entryType": "measure",
    "startTime": 2160161.5,
    "duration": 0
}

自定义measure示例

performance.measure('custom-measure', {
  detail: {'user':'yma16'},
  start: 100,
  end: 150,
});

运行结果

{
	detail: {'user':'yma16'},
    "name": "custom-measure",
    "entryType": "measure",
    "startTime": 100,
    "duration": 50
}

⭐计算echarts渲染的持续时间

渲染echarts逻辑如下

function renderEchartBar() {
    // 基于准备好的dom,初始化echarts实例
    const domInstance = document.getElementById('barChartId')
    if (domInstance) {
        domInstance.removeAttribute('_echarts_instance_')
    }
    else {
        return
    }
    const myChart = echarts.init(domInstance);
    const option = {
        backgroundColor: 'rgba(0,0,0,0)',//背景色
        title: {
            text: '中国地图',
            subtext: 'china',
            color: '#fff'
        },
        visualMap: { // 设置视觉映射
            min: 0,
            max: 20,
            text: ['最高', '最低'],
            realtime: true,
            calculable: true,
            inRange: {
                color: ['lightskyblue', 'yellow', 'orangered']
            }
        },
        geo: {
            // 经纬度中心
            // center: state.centerLoction,
            type: 'map',
            map: 'chinaJson', // 这里的值要和上面registerMap的第一个参数一致
            roam: false, // 拖拽
            nameProperty: 'name',
            geoIndex: 1,
            aspectScale: 0.75, // 长宽比, 默认值 0.75
            // 悬浮标签
            label: {
                type: 'map',
                map: 'chinaJson', // 这里的值要和上面registerMap的第一个参数一致
                // roam: false, // 拖拽
                // nameProperty: 'name',
                show: true,
                color: '#333',
                formatter: function (params) {
                    return params.name
                },
                // backgroundColor: '#546de5',
                align: 'center',
                fontSize: 10,
                width: (function () {
                    // let n = parseInt(Math.random() * 10)
                    return 110
                })(),
                height: 50,
                shadowColor: 'rgba(0,0,0,.7)',
                borderRadius: 10
            },
            zoom: 1.2
        },
        tooltip: {
            show: true,
            position: ['10%', '10%'],
            formatter: (params) => {
                const { name } = params.data
                const filterData = filterMapName(name)
                let isTruthCount = 0
                const strInfo = filterData.map(item => {
                    if (item.status === '有效') {
                        isTruthCount++
                    }
                    return `<img src=${item.imgSrc} width='20' height='20'/>&nbsp; ${item.name}&nbsp;(${item.status})`
                }).join('<br>')
                state.provinceIsTruthCount = isTruthCount
                const value = filterData.length
                return `地区:${name}<br>
                报名总人数:${value} <br>
                有效报名人数:${isTruthCount}<br>
                人员信息:<br>${strInfo}`
            }
        },
        series: [
            // 坐标点的热力数据
            {
                data: state.airData,
                geoIndex: 0, // 将热力的数据和第0个geo配置关联在一起
                type: 'map',
                roam: false,
                itemStyle: {
                    normal: {
                        areaColor: "rgba(0, 0, 0, 0)",
                        borderWidth: 8, //设置外层边框
                        borderColor: "rgba(135,235, 45, 1)",
                        shadowColor: "rgba(135,235, 45, 1)",
                        shadowBlur: 40, //地图外层光晕
                    },
                },
            },
            {
                type: 'effectScatter',
                // 渲染显示
                zlevel: 3,
                showEffectOn: 'render',
                data: state.locationGis, // 配置散点的坐标数据
                coordinateSystem: 'geo', // 指明散点使用的坐标系统
                rippleEffect: {
                    // 缩放
                    scale: 4,
                    // 涟漪的颜色
                    color: '#cf6a87',
                    // 波纹数量
                    number: 2,
                    // 扩散方式 stroke(线条) fill(区域覆盖)
                    brushType: 'fill'
                },
                // 形状
                symbol: 'circle'
            },
        ],
    }

    console.log('option', option)
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option, true);
    // 监听
    state.echartInstance = myChart;
    myChart.on('click', function (params) {
        console.log('params', params)
        filterName(params.name)
    });
    window.onresize = myChart.resize;
}

在开始时刻添加标记

performance.mark('render-echart-start')

在结束时刻添加标记,然后调用measure获取最近一次标记的持续时间

performance.mark('render-echart-end')
const measure=performance.measure('render-echart-duration','render-echart-start','render-echart-end')
const duration=measure.duration

计算地图渲染的效果,耗时 29.30ms

render

vue3demo inscode项目

⭐结束

本文分享到这结束,如有错误或者不足之处欢迎指出!
future city

👍 点赞,是我创作的动力!
⭐️ 收藏,是我努力的方向!
✏️ 评论,是我进步的财富!
💖 最后,感谢你的阅读!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yma16

感谢支持!共勉!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值