Unity的Profiler使用

本文介绍了一个Unity项目中如何使用Profiler进行性能优化的具体实践。通过一个名为TestProfiler的脚本,展示了如何在每帧更新时对特定操作进行校验和运行,并详细记录了包括数值运算、列表操作等在内的多个子过程的性能消耗。此脚本利用Profiler.BeginSample和Profiler.EndSample方法对各个模块的执行时间进行精确测量,为开发者提供了深入理解并优化其游戏或应用性能的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using UnityEngine;
using System.Collections.Generic;
using UnityEngine.Profiling;

public class TestProfiler : MonoBehaviour
{
    int t = 10000;

    // 每帧Update都会进行校验和运行
    void Update()
    {
        Check(t); // 校验
        Run(); // 运行
    }

    void Check(int n)
    {
        Profiler.BeginSample("Check");
        CheckA(); // 校验模块A

        Profiler.BeginSample("Calculate b");
        // 数值运算
        int b = n - 100;
        if (b < 10)
            b = 10;
        Profiler.EndSample();

        CheckB(b); // 校验模块B
        Profiler.EndSample();
    }

    void CheckA()
    {
        Profiler.BeginSample("CheckA");
        Debug.Log("校验模块A");
        Profiler.EndSample();
    }

    void CheckB(int loopCount)
    {
        Profiler.BeginSample("CheckB");
        Debug.Log("校验模块B");

        Profiler.BeginSample("new List<string>");
        List<string> strList = new List<string>();
        Profiler.EndSample();

        for (int i = 0; i < loopCount; ++i)
        {
            Profiler.BeginSample("Add str to list");
            string str = string.Format("CheckB:{0}", i);
            strList.Add(str);
            Profiler.EndSample();
        }

        Debug.Log(string.Format("list count: {0}", strList.Count));
        Profiler.EndSample();
    }

    void Run()
    {
        Profiler.BeginSample("Run");
        Debug.Log("开始运行");
        DoSomething();
        Profiler.EndSample();
    }

    void DoSomething()
    {
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值