コンテンツにスキップ
Unity Burstによる直接呼び出しコードの加速例

Unity Burstによる直接呼び出しコードの加速例

2024-11-05 06:20

Burstのドキュメントやサンプルは少なく、Job方式での呼び出し以外にも、直接呼び出すこともできます。

以下は、球体のすべての頂点に対してUVを生成するサンプルコードです。Burstを使用することで約50%の高速化が見込めます。

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(); 無効

            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;
        }
    }

直接呼び出す方法は以下の通りです:

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]は、Burstにこのポインタが他のポインタとエイリアス(重複参照)していないことを伝え、安心してベクトル化を行えるようにするためのものです。NativeArrayを使用する場合は自動的に判断されるため不要ですが、ここでは独自のポインタを使用しているため、付加するのが望ましいです。

Burstによるベクトル化コードの生成には多くの制限があり、並列処理数も少ないため、Computer Shaderを使用することをお勧めします。そうすることで、さらに50%の高速化が可能です。

最終編集
hugo-builder
hugo-builder · · 自动翻译 about.md 2... · 248520b
他の貢献者
...