性能分析:针对代码片段执行消耗CPU时间估算的方式2:自定义计时和日志记录工具类
程序员文章站
2022-06-09 14:39:32
...
方式二:通过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();
}
}
}
}
}
测试打印结果如下