文章目录
封装Stopwatch工具类
用于计算执行一段代码所用的时间。
using System;
using System.Diagnostics;
using UnityEngine.Events;
/// <summary>
/// Stopwatch工具类,计算一段代码的执行时间
/// </summary>
public static class StopwatchTool
{
/// <summary>
/// 打印执行一段代码所用的时间,单位/秒
/// </summary>
/// <param name="action">执行方法</param>
/// <param name="executionNumber">执行次数,默认1次</param>
public static void PrintTime(UnityAction action, int executionNumber = 1)
{
if(executionNumber <= 0){
UnityEngine.Debug.LogWarning("Stopwatch性能测试失败!执行数应为正整数。");
return;
}
double totalMilliseconds = 0;
for (var i = 0; i < executionNumber; i++)
{
totalMilliseconds += GetTime(action).TotalMilliseconds / 1000;
}
UnityEngine.Debug.Log($"执行该代码{
executionNumber}次,用时{
totalMilliseconds}秒");
}
/// <summary>
/// 获取执行一段代码所用的时间信息
/// </summary>
/// <param name="执行方法"></param>
/// <returns></returns>
private static TimeSpan GetTime(UnityAction action){
Stopwatch timer = Stopwatch.StartNew();//声明计时器
timer.Start();//声明计时器
action?.Invoke();//要测试的代码
timer.Stop();//停止计时器
return timer.Elapsed;//返回时间信息
}
}
测试调用,打印执行一段代码10000次需要多少秒
public class ToolsTest : MonoBehaviour {
private void Start() {
StopwatchUtility.PrintTime(Execute, 10000);
}
void Execute(){
"测试字符".GetType();
}
}
结果
完结
赠人玫瑰,手有余香!如果文章内容对你有所帮助,请不要吝啬你的点赞评论和关注
,你的每一次支持
都是我不断创作的最大动力。当然如果你发现了文章中存在错误
或者有更好的解决方法
,也欢迎评论私信告诉我哦!
好了,我是向宇
,https://xiangyu.blog.csdn.net
一位在小公司默默奋斗的开发者,闲暇之余,边学习边记录分享,站在巨人的肩膀上,通过学习前辈们的经验总是会给我很多帮助和启发!如果你遇到任何问题,也欢迎你评论私信或者加群找我, 虽然有些问题我也不一定会,但是我会查阅各方资料,争取给出最好的建议,希望可以帮助更多想学编程的人,共勉~