Unity2019 增量式GC(使用时间片段执行GC,减少卡顿)

Posted 那个妹子留步

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity2019 增量式GC(使用时间片段执行GC,减少卡顿)相关的知识,希望对你有一定的参考价值。

 xasset 的资源回收策略是异步渐进式回收策略,在这种机制下,单帧最大回收多少资源会根据 CPU 的利用率动态计算,从而保证程序的流畅性。如果没有这个机制,试想一帧释放 50 个 ab, 每个 ab 10ms,这一帧就会需要 500ms,必然会造成严重的卡顿问题。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System.Threading;
using System.Linq;
using System;
using System.Diagnostics;

public class DebugUIManager : MonoBehaviour


    [Header("Components")]
    [SerializeField] private TMP_Text cpuCounterText;

    [Header("Settings")]
    [Tooltip("In which interval should the cpu usage be updated?")]
    [SerializeField] private float updateIntetval = 1;

    [Tooltip("The amount of physical CPU cores")]
    [SerializeField] private int processorCount;

    [Header("Output")]
    public float CpuUsage;

    private Thread _cpuThread;
    private float _lasCpuUsage;

    // Start is called before the first frame update
    void Start()
    
        Application.runInBackground = true;

        cpuCounterText.text = "0% CPU";

        _cpuThread = new Thread(UpdateCPUUsage)
        
            IsBackground = true,
            Priority = System.Threading.ThreadPriority.BelowNormal
        ;


        _cpuThread.Start();
    

    private void OnValidate()
    
        processorCount = SystemInfo.processorCount / 2;
    

    private void OnDestroy()
    
        _cpuThread?.Abort();
    

    // Update is called once per frame
    void Update()
    
        if (Mathf.Approximately(_lasCpuUsage, CpuUsage)) return;

        if (CpuUsage < 0 || CpuUsage > 100) return;

        cpuCounterText.text = CpuUsage.ToString("F1") + "% CPU";


        _lasCpuUsage = CpuUsage;

    

   private void UpdateCPUUsage()
    
        var lastCPUTime = new TimeSpan(0);

        while (true)
        
            var cputime = new TimeSpan(0);

            //Get a list of all running processes in this PC
            var AllProcess = Process.GetProcesses();

            //Sum up the total processor time of all running processes
            cputime = AllProcess.Aggregate(cputime, (current, process) => current + process.TotalProcessorTime);

            var newCPUTime = cputime - lastCPUTime;

            lastCPUTime = cputime;

            CpuUsage = 100f * (float)newCPUTime.TotalSeconds / updateIntetval / processorCount;

            //wait for updateInterval
            Thread.Sleep(Mathf.RoundToInt(updateIntetval * 1000));
        

 

    

以上是关于Unity2019 增量式GC(使用时间片段执行GC,减少卡顿)的主要内容,如果未能解决你的问题,请参考以下文章

在python中使用滑动窗口概念的GC倾斜方法

unity啥情况下gc不能自动回收垃圾对象

Unity优化之GC——合理优化Unity的GC

Unity优化之GC--合理优化unity的gc

UNITY性能优化丨GC攻略大全

UNITY性能优化丨GC攻略大全