C# 计算内存使用情况

    /// <summary>
    /// 打印内存占用
    /// </summary>
    /// <returns></returns>
    public static string MemoryAndCPU()
    {
        StringBuilder MemoryAndCpuStr = new StringBuilder();
        if (!GOIConfig.GetInstance().MLog.MemoryAndCpuLogs)
            return "";
        try
        {
            MemoryAndCpuStr.Clear();
            int MB_DIV = 1024 * 1024;
            int GB_DIV = 1024 * 1024 * 1024;
            //获取当前进程对象
            Process cur = Process.GetCurrentProcess();
            PerformanceCounter curpc = new PerformanceCounter("Process", "Working Set", cur.ProcessName);
            SystemInfo sys = new SystemInfo();

            string goiMemory = string.Format("{0}-{1} {2:N}KB({3}MB)", cur.ProcessName, "内存使用大小:", curpc.NextValue() / 1024, curpc.NextValue() / 1024 / 1024);
            if (GOIConfig.GetInstance().Language.ToUpper().Contains(GOIConfig.LANGUAGE_EN))
            {
                goiMemory = string.Format("{0}-{1} {2:N}KB({3}MB)", cur.ProcessName, "Memory usage size:", curpc.NextValue() / 1024, curpc.NextValue() / 1024 / 1024);
            }

            Log.GetInstance().WriteSys(goiMemory);
            string MemoryAndCpu = string.Format("\r系统CPU使用率:{0}%,系统内存使用大小:{1}MB({2}GB)", sys.CpuLoad, (sys.PhysicalMemory - sys.MemoryAvailable) / MB_DIV, (sys.PhysicalMemory - sys.MemoryAvailable) / (double)GB_DIV);
            if (GOIConfig.GetInstance().Language.ToUpper().Contains(GOIConfig.LANGUAGE_EN))
            {
                MemoryAndCpu = string.Format("\r System CPU utilization:{0}%,System memory usage size:{1}MB({2}GB)", sys.CpuLoad, (sys.PhysicalMemory - sys.MemoryAvailable) / MB_DIV, (sys.PhysicalMemory - sys.MemoryAvailable) / (double)GB_DIV);
            }
            Log.GetInstance().WriteSys(MemoryAndCpu);
            MemoryAndCpuStr.Append(goiMemory);
            MemoryAndCpuStr.Append("  " + MemoryAndCpu);
            return MemoryAndCpuStr.ToString();
        }
        catch (Exception ex)
        {
            string msg = @"第一步:cmd 输入perfmon
            发现弹出报错
            “不能添加这些计数器”
            \memorry\Available Mbytes
            \memorry\% committed bytes in use
            \memorry\cache faults/ sec
            \memorry\cache faults/ sec
            \physicalDisk(*)\% idle time
            \physicalDisk(*)\avg.disk queue length
            \network interface(*)\bytes total/sec

            第二步:cmd(管理员身份打开),输入 ”LODTCR /R”
            等一会后系统提示”……恢复成功”";
            MessageBox.Show("内存监控失败,请尝试如下操作:" + msg);
            Log.GetInstance().WriteError("MemoryAndCPU:" + ex.Message);
        }
        return "";
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值