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.欢迎大神解惑。