Unity Burst Direct Call Code Example for Acceleration
There is relatively little documentation and examples for Burst. Apart from calling via Jobs, it can also be called directly.
The following is example code for generating UVs for all vertices of a sphere. Using Burst can provide approximately a 50% speedup.
using System.Runtime.CompilerServices;
using Unity.Burst;
using Unity.Mathematics;
[BurstCompile]
public static class ParallelMethods
{
[MethodImpl(MethodImplOptions.NoInlining)]
[BurstCompile]
public static unsafe void GenUVs([NoAlias] in float3* vertices, [NoAlias] float2* uvs,
int count)
{
for (var i = 0; i < count; i += 1)
{
// Unity.Burst.CompilerServices.Loop.ExpectVectorized(); Ineffective
var p = vertices[i];
var longitude = math.atan2(p.z, p.x);
var latitude = math.asin(p.y);
uvs[i].x = longitude / math.PI2 + 0.5f;
uvs[i].y = latitude / math.PI + 0.5f;
}
}The direct call method is as follows:
void Update()
{
UVs = new Vector2[vertices.Length];
unsafe
{
fixed (Vector3* vts = vertices)
{
fixed (Vector2* uvs = UVs)
{
ParallelMethods.GenUVs((float3*)vts, (float2*)uvs, vertices.Length);
}
}
}
}[NoAlias] is used to inform Burst that this pointer does not alias with other pointers, allowing safe vectorization. If using NativeArray, this is automatically determined and not needed. Here, because we are using our own pointers, it’s best to add it.
Burst has many restrictions when generating vectorized code and offers limited parallelism. It is recommended to use Compute Shader instead, which can provide an additional 50% speedup.