zoukankan      html  css  js  c++  java
  • 通过VS2010性能分析来查找代码中那些地方最损耗资源

      在编写完成一个程序后,大家都比较关心程序的性能如何,想把程序优化得更好。很多时候凭个人直觉来优化程序是件非常不靠普的事情,即使你是一个优秀的开人员也很难准确地判断程序中那些出现问题。VS2010提供了性能分析工具就能轻松地帮我们解决这一事情。

    • 假设现在写了一个组件,很想知道组件和代码的性能情况。这个可以简单地写一个测试程序。
    View Code
        class Program
    {
    static List<Expression> mExpressions = new List<Expression>();
    static Random mRan = new Random();
    static void Main(string[] args)
    {
    try
    {
    string dbpath = @"Data Source=d:\\northwind.db;Pooling=true;FailIfMissing=false;";
    DBContext.SetConnectionDriver<SqliteDriver>(ConnectionType.Context1);
    DBContext.SetConnectionString(ConnectionType.Context1, dbpath);
    mExpressions.Add(Order.shipCountry == "Switzerland");
    mExpressions.Add(Order.shipRegion == "RJ");
    mExpressions.Add(Order.customerID.In(Customer.customerID, Customer.country == "UK"));
    mExpressions.Add(Order.customerID.In(Customer.customerID, Customer.country == "Germany"));
    mExpressions.Add(Order.orderDate > "1997-8-5");
    mExpressions.Add(Order.orderDate < "1997-12-1");
    mExpressions.Add(Order.orderDate > "1997-5-1" & Order.orderDate<"1997-11-5");
    System.Threading.Thread thread;
    for (int i = 0; i < 10; i++)
    {
    thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Test
    ));
    thread.Start();
    }

    }
    catch (Exception e_)
    {
    Console.WriteLine(e_.Message);
    }

    }
    static void Test(object obj)
    {
    while (true)
    {
    Expression exp = mExpressions[mRan.Next(mExpressions.Count - 1)];
    Console.WriteLine(exp.Count<Order>());
    System.Threading.Thread.Sleep(mRan.Next(50, 5000));
    }
    }

    }
    • 测试程序写好后可以通过VS2010分析菜单里选择启用性能向导

    • 选择CPU采样后就选择需要分析的项目

    • 测试项目选择完成后就可以运行分析,结束分析后VS2010会提供个详细报告文档

    • 从分析结果来看GetConnection这个方法占用的比例是最严重的,我们可以点击进去看下这函数倒做了些什么,那些代码损耗得最利害。

    • 从上面结果来看损耗最利害的是创建ConnectionContext对象,这个时候我们可以进一步点击进去看个究竟

    • 这个方法还没发现真正的原因,我们继续往下走

      到了这里发现原来是connection.Open方法占用了大部分资源,这个时候就想到这个测试程序跑这么久为什么连接打开这么损耗资源,是不是连接池没有开启导致每次操作都进行数据库连接操作呢?

      其实VS2010给我们提供的分析工具真得很轻松就可以让我们了解到程序代码状况,从而优化程序的代码。如果有这烦脑的朋友不防试下:)
     

    访问Beetlex的Github
  • 相关阅读:
    try和catch
    获取地址栏参数(E积分项目)
    正则验证,只能输入数字,每四位隔一个空格。
    E积分项目总结(绑卡页 第一步)
    本地存储localStorage用法详解
    python os 模块介绍
    生成器迭代器
    python 魔法方法
    匿名函数
    python自定义函数和内置函数
  • 原文地址:https://www.cnblogs.com/smark/p/2208039.html
Copyright © 2011-2022 走看看