获取代码开始执行的时间和某段代码运行的时间

【前言】

        有时我们需要知道某段代码在什么时候开始运行,以及某处逻辑运行了多长时间,需要有一个时间记录的工具。

【实现】

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();
        }
    }
}

【输出】

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值