[unity] how to parallel for loop

sequence

Parallel for loop

You can do it in the compute shader, but you need to know a bunch of APIs first, such as setBuffer

It seems that the job system of unity can also be done, but that also needs to know a bunch of APIs first

These are big and comprehensive. Is there one that is less powerful but easier to use?

Just like C++'s openmp, just add a few lines.

Unity and c# and multithreading

(84 messages) Unity multithreading knowledge points record_unity multithreading_Gouzi's blog tortured by code-CSDN blog

In general, it can be used. 

How does C# execute a for loop in parallel?

Parallel For Loop in C# with Examples - Dot Net Tutorials

A picture will make it clear:

Get some code and be more specific.

// 串行的for循环
using System;
namespace ParallelProgrammingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("C# For Loop");
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();
        }
    }
}
// 并行的for循环【只要稍微改一改,串行for就变成并行for了】
using System;
using System.Threading.Tasks; // 01.加一个头文件

namespace ParallelProgrammingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("C# Parallel For Loop");
            
            //It will start from 1 until 10
            //Here 1 is the start index which is Inclusive
            //Here 11 us the end index which is Exclusive
            //Here number is similar to i of our standard for loop
            //The value will be store in the variable number
            Parallel.For(1, 11, number => {
                Console.WriteLine(number);
            }); // 02.修改一下for循环的写法
            Console.ReadLine();
        }
    }
}

Instrumentation and Timing

This method can be used to count the time and judge whether the parallel execution of the for loop has improved the efficiency. 

(84 messages) c# statistics code execution time_c# code execution time_jenny_paofu's blog-CSDN blog

System.DateTime start = System.DateTime.Now;

//耗时的for循环

System.DateTime end = System.DateTime.Now;
print("用时:" + (end - start));

postscript

This is a relatively simple way of writing, of course, there are many limitations:

  • A CPU has far fewer cores than a GPU
  • Locking and other issues are not considered here

Guess you like

Origin blog.csdn.net/averagePerson/article/details/130988872
Recommended