C# 代码执行效率

来源:互联网 发布:ubuntu音乐播放器 编辑:程序博客网 时间:2024/06/16 02:22

C#代码执行效率

有时候想查看执行一些代码花费了多长时间,或者看某些代码的效率。怎么办呢。
下面通过使用C#方法检测一下

新建一个Unity工程,在场景中创建一个GameObject,创建脚本 Efficiency.cs
代码如下

using UnityEngine;using System.Collections;using System.Diagnostics;public class Efficiency : MonoBehaviour {    // Update is called once per frame    void Update () {        if (Input.GetKeyDown(KeyCode.A))        {            Stopwatch stopWatch = new Stopwatch();            stopWatch.Start();            Call();            stopWatch.Stop();            UnityEngine.Debug.Log("A    " + stopWatch.ElapsedMilliseconds);        }        if (Input.GetKeyDown(KeyCode.D))        {                     Stopwatch stopWatch = new Stopwatch();            stopWatch.Start();            int number = 100;            Call(number);            stopWatch.Stop();            UnityEngine.Debug.Log("D    " + stopWatch.ElapsedMilliseconds);        }    }    private void Call()    {        for (int i = 0; i < 100000; i++)        {            GameObject.Find("GameObject");        }    }    private void Call(int num)    {        for (int i = 0; i < 10000000; i++)        {            num++;        }    }}

运行项目,分别点击 A, D

这里写图片描述

看下花费时间

一个执行 100 000 次花费 88 毫秒
一个执行 10 000 000 次花费 64 毫秒

0 0
原创粉丝点击