[unity]如何并行for循环

并行for循环

计算着色器里可以弄,但是那个得先了解一堆api,比如什么setBuffer

unity 的 job system好像也可以弄,但是那个也得先了解一堆api

这些都是大而全的,有没有那种,没那么神通广大但是比较容易上手的?

就像C++的openmp,加几行就行了。

unity与c#与多线程

(84条消息) Unity多线程知识点记录_unity 多线程_被代码折磨的狗子的博客-CSDN博客

总的来说,可以用。 

C#如何并行执行for循环?

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

一个图就说明白了:

搞点代码,更具体一些。

// 串行的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();
        }
    }
}

插桩与计时

可以用这种方法,来统计时间,判断并行执行的for循环对效率有没有提升。 

(84条消息) c#统计代码执行时间_c# 代码执行时间_jenny_paofu的博客-CSDN博客

System.DateTime start = System.DateTime.Now;

//耗时的for循环

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

后记

这是比较简单的一种写法,当然局限也很多:

  • CPU的核本来就远远少于GPU
  • 这里没考虑加锁等问题

猜你喜欢

转载自blog.csdn.net/averagePerson/article/details/130988872
今日推荐