[unity]如何并行for循环

文章介绍了在C#中如何使用Parallel.For实现并行for循环,对比了Unity中的计算着色器和JobsSystem,强调了简单易用的特性。并提供了代码示例,展示如何将串行循环转换为并行,以及如何通过计时来评估效率提升。文章最后提到了这种方法的局限性,如CPU核心数量和未处理的同步问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

并行for循环

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

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

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

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

unity与c#与多线程

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

总的来说,可以用。 

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的博客-优快云博客

System.DateTime start = System.DateTime.Now;

//耗时的for循环

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

后记

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值