【前言】
有时我们需要知道某段代码在什么时候开始运行,以及某处逻辑运行了多长时间,需要有一个时间记录的工具。
【实现】
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProfileTimer
{
private class ProfileItem
{
public string name;
public float time;
public bool used;
public void Reset()//重置
{
name = "";
time = 0.0f;
used = false;
}
}
//记录栈
private static Stack<ProfileItem> RecordStack = new Stack<ProfileItem>();
//简单的对象池
private static Queue<ProfileItem> ItemPool = new Queue<ProfileItem>();
private static List<string> logList = new List<string>();
public static void BeginRecord(string name)
{
if (ItemPool.Count > 0)
{
if (!ItemPool.Peek().used)
{
ProfileItem item = ItemPool.Dequeue();//取出一个对象
item.name = name;
item.time = Time.realtimeSinceStartup;
item.used = true;
RecordStack.Push(item);
}
}
else
{
//池子里面没有可能对象了,生成一个对象并加入,然后再取出
ItemPool.Enqueue(new ProfileItem());
BeginRecord(name);
}
}
public static void EndRecord()
{
if (RecordStack.Count == 0)
{
Debug.LogError("no record");
return;
}
else
{
float runTime = 0f;
ProfileItem item = RecordStack.Pop();
runTime = Time.realtimeSinceStartup - item.time;
string logText = item.name + ":" + "startTime:" + item.time + "||runTime:" + runTime;
Debug.Log(logText);//立马打出log
//logList.Add(logText);//统一控制打印
//重新放入对象池
item.Reset();
ItemPool.Enqueue(item);
}
}
public static void PrintLog()
{
foreach (string s in logList)
{
Debug.Log(s);
}
logList.Clear();
}
}
【使用】
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour
{
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))//按空格键表示开始记录
{
ProfileTimer.BeginRecord("按下空格");
}
if (Input.GetKeyDown(KeyCode.Escape))//按退出键表示这段记录结束
{
ProfileTimer.EndRecord();
}
}
}