性能分析:针对代码片段执行消耗CPU时间估算的方式2:自定义计时和日志记录工具类

方式二:通过Stopwatch对象来实现计时功能,并加上Log日志可以实现通过看Log日志来查看该段代码执行所消耗的时间。封装的计时器脚本类如下:

using System;
using System.Diagnostics;
/*
 * Author:W
 * 代码执行时间计算工具:通过Stopwatch对象来实现
 */
public class ScrptProcessTimer : IDisposable
{

    /// <summary>
    /// 定时器名称
    /// </summary>
    private string timerName;
    /// <summary>
    /// 期望运行的次数
    /// </summary>
    private int numTests;

    private Stopwatch stopwatch;

    /// <summary>
    /// 为API执行加上计算耗时的功能
    /// </summary>
    /// <param name="timerName"></param>
    /// <param name="numTests"></param>
    public ScrptProcessTimer(string timerName, int numTests)
    {
        this.timerName = timerName;

        this.numTests = numTests;
        if (this.numTests <= 0)
            this.numTests = 1;

        stopwatch = Stopwatch.StartNew();
    }

    /// <summary>
    /// 当使用Using()块结束时自动调用
    /// </summary>
    public void Dispose()
    {
        if (stopwatch == null) return;
        
        stopwatch.Stop();

        float ms = stopwatch.ElapsedMilliseconds;
        
        UnityEngine.Debug.Log(string.Format("{0} finished {1: 0.00} milliseconds total {2: 0.000000} milliseconds per-test for {3} tests", timerName,ms,ms/numTests,numTests));        
    }
}

测试脚本如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 /*
  * Author:W
  * 代码执行耗时计算方式2:通过Stopwatch对象来实现
  */
public class ScroptProvess2 : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}


	private void Test()
	{
		Debug.Log("=====1======");
	}
	
	// Update is called once per frame
	void Update () {

		if (Input.GetKeyDown(KeyCode.A))
		{
			int numTests = 1000;
			using (new ScrptProcessTimer("Stopwatch Test", numTests))
			{
				for (int i = 0; i < numTests; i++)
				{
					Test();
				}
			}
		}
	}
}

测试打印结果如下
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Data菌

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值