zoukankan      html  css  js  c++  java
  • 使用System.Diagnostics.Stopwatch对比程序段运行时间

       System.Diagnostics.Stopwatch 可以用来测量程序段的运行时间,一般情况下在有多种途径(算法)来实现同一功能时,我们可能想对这两种方法进行一个比较,这个时候简单的使用下Stopwatch就可以有个大致的概念.

     比方下面两段代码,功能都是获取<td .....>....</td> 中的内容,里面可能包含html标签(table,div,td等等),其中一种办法是单个字符的读取,借助堆栈来实现截取,代码如下:

     

    private string GetDescription()
            {
                int left = 1;
                Stack<int> stack = new Stack<int>();
                int s = Content.IndexOf(DescriptionFlag);
                int e = Content.IndexOf(DesEndFlag,s);
                string str = Content.Substring(s, e - s).Trim() ;
                int index = 1;
                stack.Push(left);
                while (stack.Count >0 && index<str.Length)
                {
                    string c = str.Substring(index, 1);
                    if (c == "<")
                    {
                        if (str.Substring(index, 4).IndexOf("<td") >= 0)
                        {
                            stack.Push(left);
                        }
                        if (str.Substring(index, 4).IndexOf("</td") >= 0)
                        {
                             stack.Pop();
                        }
                    }
             
                     index++;
                   
                }
                return str.Substring(DescriptionFlag.Length,index-DescriptionFlag.Length-1).Trim();

            }

     -----------------------

     另外一种就是采用正规表达式中的平衡组,不过这个语法太麻烦了,配置了半天,终究还是没匹配出来,于是放弃了,
    后来发现<td ....>....</td> ....后面一段代码是特殊的,于是就采用 <td....>(.*?)</td>....这样的形式来直接匹配.
    下面是Stopwatch的基本使用,对比这两种方法的执行时间
            System.Diagnostics.Stopwatch w1 = new System.Diagnostics.Stopwatch();
                w1.Start();
                product.Description = GetMatch(Content, RegDescription, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                w1.Stop();
                long t1 = w1.ElapsedMilliseconds; //使用正规表达式
                w1.Reset();
                w1.Start();
                string des = GetDescription(); //使用stack获取
                w1.Stop();
                long t2 = w1.ElapsedMilliseconds;

    -----------------

     结果发现使用正则表达式速度要比借助于stack的方法快,而且当<td>...</td>数据量变大时,使用stack实现的速度更慢,而使用正则表达式的速度就相对稳定, 当然作为一个程序员,很多情况下都会使用正则表示式,但要知道内部实现,具体的算法复杂度就估计没几人了,也希望有牛人给点这方面的资料,也让用了"一辈子"正则的人死个明白(^_^严重了),
    另外匹配<td...><html></td>这样形式的平衡组到底怎么写也望有人给个代码,本人在此谢过了.
                                                                                              ------谨慎的发布到新手区

  • 相关阅读:
    最短路-dij
    链式前向星
    B树、B+树
    C++类
    差分约束
    数位DP
    Markdown编辑器:表格
    git使用笔记
    leetcode 162. 寻找峰值(二分)
    python matplotlib包的安装注意事项:报错——No such file or dir : tmp/matplotlib-xxxxxx
  • 原文地址:https://www.cnblogs.com/wdfrog/p/1350809.html
Copyright © 2011-2022 走看看