zoukankan      html  css  js  c++  java
  • 分析CPU使用率不断增加的原因

    工程中发现引起的问题:

      结合别的朋友的意见,我的优化思路是:

        1、排查是否内存泄漏

            经过反复查询代码,未发现有内存泄漏(可以自己百度搜索C#内存泄漏的原因)。可以通过任务管理器分析是否有内存泄漏,打开任务管理器-性能-打开资源监视器,然后可以检查CPU、内存、磁盘、网络等信息

        2、排查是否有线程未关闭

            线程未关闭引起的话,开辟线程后在不用时记得

            thread.DisableComObjectEagerCleanup();
                          thread.Abort();

                3、另外可以通过控制程序在那些个CPU中使用,从而避免打开不必要的CPU消耗。具体实现代码找度娘。

          参考:Process来控制主线程

          

     1 public static void SetProcess()
     2         {
     3             Process p = new Process();
     4             p.StartInfo.FileName = System.IO.Directory.GetCurrentDirectory() + "\Test.exe";
     5             p.StartInfo.RedirectStandardError = true;
     6             p.StartInfo.RedirectStandardOutput = true;
     7             p.StartInfo.UseShellExecute = false;
     8             p.StartInfo.CreateNoWindow = true;
     9             p.Start();
    10 
    11             //设置CPU使用数,这里使用了CPU0和CPU1
    12             p.ProcessorAffinity= (IntPtr)(0x0001 | 0x0002);
    13             p.Close();
    14             p.Dispose();
    15         }
    View Code

        4、CPU的使用率太高的话,线程上可以加上 时间间隔来减少分子,比如你的线程跑的速度是10秒每次和10毫秒每次效果上就完全就不同了(根据电脑的配置不同效果不一样的),或者直接用while(true);l来检测CPU的使用率更能直观看出。

        5、读完垃圾回收机制后,重写做一个垃圾回收处理。比如一个线程中1秒钟强制回收一次。这样处理后代码消耗内存基本稳定了,不会爆表。在没有内存泄漏的情况,推荐这种方式,暴力回收。

          代码:

     1 /// <summary>
     2         /// 获取为关联的进程分配的专用内存量(以字节为kb)。
     3         /// </summary>
     4         /// <returns></returns>
     5         public static long ReadProcessMemory()
     6         {
     7             long usedMemory = 0;
     8             try
     9             {
    10                 Process proc = Process.GetCurrentProcess();
    11                 usedMemory = proc.PrivateMemorySize64 / 1024;
    12             }
    13             catch (Exception ex)
    14             {
    15                 Utils.Log.Log.DataExport("logs", ex.ToString());
    16             }
    17             return usedMemory;
    18         }
    View Code

       6、SetProcessWorkingSetSize,然后特别注意下https://blog.csdn.net/weixin_30607659/article/details/97205705与http://blog.sina.com.cn/s/blog_49f8960e0100081x.html的说法,现在内存消耗一直是以龟速慢慢增加,又要砸时间搞这事了 。看我C#垃圾回收机制详解https://www.cnblogs.com/wwj1992/p/8387360.html,搞到最后估计大家也会经放弃治疗了。最后 希望看完的朋友有啥好意见可以分享给我,谢谢。

     

          

  • 相关阅读:
    mysql 8 nodejs连不上
    render与vue组件和注册
    0424 前端笔记
    0423
    任务
    使用async await 封装 axios
    [Java] Spring 3.0 01/02/03/04/05 -自设源代码
    [Java] Spring3.0 360百科介绍
    [Java] Spring3.0
    [Java] Spring3.0 面向抽象(接口)编程
  • 原文地址:https://www.cnblogs.com/LiuL123-321/p/12133345.html
Copyright © 2011-2022 走看看