美文网首页
[个人框架 C_Framework] (EasyTool) Ta

[个人框架 C_Framework] (EasyTool) Ta

作者: hh5460 | 来源:发表于2018-10-26 11:18 被阅读0次
using System;
using System.Diagnostics;

public class TakeTimer
{
    static Stopwatch _sw;
    static Stopwatch sw
    {
        get
        {
            if (_sw == null)
            {
                _sw = new Stopwatch();
            }
            return _sw;
        }
    }

    //代码块名称
    static string codeName;

    /// <summary>
    /// 即不使用上方共用sw,通过独立的Stopwatch执行,这样可以对多个同时执行的块分别统计
    /// </summary>
    /// <param name="codeName">代码块名称,主要为了可阅读性,随便填</param>
    /// <param name="action">委托代码</param>
    public static void IndependentTakeTimer(string codeName, Action action)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        if (action != null)
        {
            action();
        }
        stopwatch.Stop();
        UnityEngine.Debug.Log(codeName + " take time:" + stopwatch.Elapsed);
    }

    /// <summary>
    /// 计算一段代码执行耗时
    /// </summary>
    /// <param name="codeName">代码块名称,主要为了可阅读性,随便填</param>
    /// <param name="action">委托代码</param>
    public static void TakeTimerAction(string _codeName, Action action)
    {
        codeName = _codeName;
        sw.Start();
        if (action != null)
        {
            action();
        }
        sw.Stop();

        UnityEngine.Debug.Log(codeName + " take time:" + sw.Elapsed);
        sw.Reset();
    }

    /// <summary>
    /// 与上面直接传入委托的方式不同,该方法写在需要测试的代码块开头处
    /// </summary>
    public static void StartTakeTimer(string _codeName)
    {
        codeName = _codeName;
        sw.Start();
    }

    /// <summary>
    /// 与上上面直接传入委托的方式不同,该方法写在需要测试的代码块结尾处
    /// </summary>
    public static void StopTakeTimer()
    {
        sw.Stop();
        UnityEngine.Debug.Log(codeName + " take time:" + sw.Elapsed);
        sw.Reset();
    }
}

演示

    void Start()
    {

        TakeTimer.StartTakeTimer("StartTakeTimer循环输出50000次");
        for (int i = 0; i < 50000; i++)
        {
            Debug.Log("Debug111 TakeTimer");
        }
        TakeTimer.StopTakeTimer();


        TakeTimer.TakeTimerAction("TakeTimerAction循环输出50000次", () =>
        {
            for (int i = 0; i < 50000; i++)
            {
                Debug.Log("Debug222 TakeTimer");
            }
        });

        TakeTimer.IndependentTakeTimer("IndependentTakeTimer循环输出50000次", () =>
        {
            for (int i = 0; i < 50000; i++)
            {
                Debug.Log("Debug333 TakeTimer");
            }
        });
    }
image.png

相关文章

网友评论

      本文标题:[个人框架 C_Framework] (EasyTool) Ta

      本文链接:https://www.haomeiwen.com/subject/khsktqtx.html