Search Unity

CPU usage is 50% maximun

Discussion in 'Editor & General Support' started by Kryber, Mar 18, 2014.

  1. Kryber

    Kryber

    Joined:
    Apr 14, 2013
    Posts:
    92
    Hi. In a long algorithm in unity the maximum CPU usage is 50%. I have a dual-core, then the other processor remains unused. This results in a considerable increase in computation time. How can I use both the CPU so that the duration of the calculation is less? Thanks in advance :)
     
  2. Philip-Rowlands

    Philip-Rowlands

    Joined:
    May 13, 2013
    Posts:
    353
    You'd have to look into multithreading. The problem here is that Unity itself isn't entirely threadsafe: if you try using threads to do stuff like adjust the position of a transform, it will throw errors. The reason for this is so that during the Update loop, everything in the scene is in a known state for the main thread.

    However, there is a way around this: make your code not depend on Monobehaviour by creating customised classes that don't interact very much with Unity objects. Here is a pretty good article on how to get around it, with a multithreading package available for download at the bottom. Hope this helps.
     
  3. Kryber

    Kryber

    Joined:
    Apr 14, 2013
    Posts:
    92
    Thanks for your reply.. but Oh my god it is so difficulty D:
     
  4. Brainswitch

    Brainswitch

    Joined:
    Apr 24, 2013
    Posts:
    270
    Isn't entirely thread safe? Heh... Reading writing almost any variable on a subclass of UnityEngine.Object will throw errors or just silently fail. I've used Loom (from unitygems, not the other costly one) but then I found, the seemingly quite unknown, Concurrency Kit from Spicy Pixel.

    It's a port of the Task Parallel Library, a library included in later versions of .NET than Unity's Mono, and it has been adapted to fully work with Unity's coroutines. It's very easy to use:

    Code (csharp):
    1. // Do something on another thread
    2. Task task = Task.Factory.StartNew(() => GenerateData(data));
    3. // Then do something on the Unity main thread
    4. task.ContinueWith(t)=> InsertIntoUnity(data));
    This will call GenerateData on another thread, wait until it is finished (without blocking Unity's main thread) and then call InsertIntoUnity on Unity's main thread. Concurrency Kit is also free.