I write a multiple frames job just like this. When I push space, It takes about 1000+ ms at first frame then takes 10+ ms in the next frames. Is this normal or how can I write a job that cost few time per frame until it completed?
using System;
using System.Collections;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine;
public class JobTest : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
inputList = new NativeList<int>(1000, Allocator.Persistent);
for (int i = 0; i < 1000; i++)
{
inputList.Add(i);
}
outputList = new NativeList<float>(1000, Allocator.Persistent);
}
private void OnDestroy()
{
inputList.Dispose();
outputList.Dispose();
}
private NativeList<int> inputList;
private NativeList<float> outputList;
private bool blocking;
private JobHandle _handle;
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
outputList.Clear();
outputList.Length = 1000;
TimeCostJob timeCostJob = new TimeCostJob()
{
inputList = inputList,
outputList = outputList
};
_handle = timeCostJob.Schedule(1000, 10, default);
StartCoroutine(CompleteBlocking());
Debug.Log($"start at {Time.frameCount}");
}
}
private IEnumerator CompleteBlocking()
{
while (!_handle.IsCompleted)
{
yield return null;
}
_handle.Complete();
Debug.Log($"complete at {Time.frameCount}");
}
}
public struct TimeCostJob : IJobParallelFor
{
[ReadOnly]
public NativeList<int> inputList;
[WriteOnly]
public NativeArray<float> outputList;
public void Execute(int index)
{
for (int i = 0; i < inputList[index]; i++)
{
var total = 0f;
for (int j = 0; j < i; j++)
{
var output = math.sin(i) * math.log(i);
total += output;
}
outputList[index] = total;
}
}
}