Unity jobsystem 和 burst编译器代码演示及效率测试

Unity jobsystem 和 burst编译器代码演示及效率测试


最近看了相关内容做了个测试

直接上代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Burst;
using Unity.Jobs;
using Unity.Collections;
using System.Diagnostics;
public class NewBehaviourScript : MonoBehaviour
{
JobHandle handle;
public NativeArray resultArray;
void Start()
{

}
private void Update() {
    if(Input.GetKeyDown(KeyCode.P))
    {
        DontUseJobSystem();
        UseJobSystemNoBurst();
        UseJobSystemAndBurst();
    }
}
void DontUseJobSystem()
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    UnityEngine.Debug.Log("DontUseJobSystem start time = " + sw.ElapsedMilliseconds);
    int num = 0;
    for(int i = 0;i< 1000000000;i++)
    {
        num++;
    }
    sw.Stop();
    UnityEngine.Debug.Log("num = " + num);
    UnityEngine.Debug.Log("DontUseJobSystem end time = " + sw.ElapsedMilliseconds);
}
void UseJobSystemNoBurst()
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    UnityEngine.Debug.Log("UseJobSystemNoBurst start time = " + sw.ElapsedMilliseconds);
    resultArray = new NativeArray<int>(new int[]{1,2},Allocator.Persistent);
    TestJobNoBurst job = new TestJobNoBurst();
    job.resultArray = resultArray;
    handle = job.Schedule();
    handle.Complete();
    sw.Stop();
    UnityEngine.Debug.Log("num = " + resultArray[0]);
    resultArray.Dispose();
    UnityEngine.Debug.Log("UseJobSystemNoBurst end time = " + sw.ElapsedMilliseconds);
}
void UseJobSystemAndBurst()
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    UnityEngine.Debug.Log("UseJobSystemAndBurst start time = " + sw.ElapsedMilliseconds);
    resultArray = new NativeArray<int>(new int[]{1,2},Allocator.Persistent);
    TestJob job = new TestJob();
    job.resultArray = resultArray;
    handle = job.Schedule();
    handle.Complete();
    sw.Stop();
    UnityEngine.Debug.Log("num = " + resultArray[0]);
    resultArray.Dispose();
    UnityEngine.Debug.Log("UseJobSystemAndBurst end time = " + sw.ElapsedMilliseconds);
}

}
public struct TestJobNoBurst:IJob
{
public NativeArray resultArray;
public void Execute()
{
int num = 0;
for(int i = 0;i< 1000000000;i++)
{
num++;
}

    resultArray[0] = num;
}

}
[BurstCompile(CompileSynchronously = true)]
public struct TestJob:IJob
{
public NativeArray resultArray;
public void Execute()
{
int num = 0;
for(int i = 0;i< 1000000000;i++)
{
num++;
}

    resultArray[0] = num;
}

}

运行结果
在这里插入图片描述
jobmanager结合burst执行效率非常强。有一点疑问的是,重复执行相同代码UseJobSystemAndBurst消耗的时间几乎为0.欢迎大神解惑。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值