将不确定变为确定~老赵写的CodeTimer是代码性能测试的利器

简介:

首先,非常感谢赵老大的CodeTimer,它让我们更好的了解到代码执行的性能,从而可以让我们从性能的角度来考虑问题,有些东西可能我们认为是这样的,但经理测试并非如何,这正应了我之前的那名话:“机器最能证明一切”!

费话就不说了,看代码吧:

  1     /// <summary>
  2     /// 执行代码规范
  3     /// </summary>
  4     public interface IAction
  5     {
  6         void Action();
  7     }
  8 
  9     /// <summary>
 10     /// 老赵的性能测试工具
 11     /// </summary>
 12     public static class CodeTimer
 13     {
 14         [DllImport("kernel32.dll", SetLastError = true)]
 15         static extern bool GetThreadTimes(IntPtr hThread, out long lpCreationTime, out long lpExitTime, out long lpKernelTime, out long lpUserTime);
 16 
 17         [DllImport("kernel32.dll")]
 18         static extern IntPtr GetCurrentThread();
 19         public delegate void ActionDelegate();
 20         private static long GetCurrentThreadTimes()
 21         {
 22             long l;
 23             long kernelTime, userTimer;
 24             GetThreadTimes(GetCurrentThread(), out l, out l, out kernelTime, out userTimer);
 25             return kernelTime + userTimer;
 26         }
 27         static CodeTimer()
 28         {
 29             Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
 30             Thread.CurrentThread.Priority = ThreadPriority.Highest;
 31         }
 32         public static void Time(string name, int iteration, ActionDelegate action)
 33         {
 34             if (String.IsNullOrEmpty(name))
 35             {
 36                 return;
 37             }
 38             if (action == null)
 39             {
 40                 return;
 41             }
 42 
 43             //1. Print name
 44             ConsoleColor currentForeColor = Console.ForegroundColor;
 45             Console.ForegroundColor = ConsoleColor.Yellow;
 46             Console.WriteLine(name);
 47 
 48             // 2. Record the latest GC counts
 49             //GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
 50             GC.Collect(GC.MaxGeneration);
 51             int[] gcCounts = new int[GC.MaxGeneration + 1];
 52             for (int i = 0; i <= GC.MaxGeneration; i++)
 53             {
 54                 gcCounts[i] = GC.CollectionCount(i);
 55             }
 56 
 57             // 3. Run action
 58             Stopwatch watch = new Stopwatch();
 59             watch.Start();
 60             long ticksFst = GetCurrentThreadTimes(); //100 nanosecond one tick
 61             for (int i = 0; i < iteration; i++) action();
 62             long ticks = GetCurrentThreadTimes() - ticksFst;
 63             watch.Stop();
 64 
 65             // 4. Print CPU
 66             Console.ForegroundColor = currentForeColor;
 67             Console.WriteLine("\tTime Elapsed:\t\t" +
 68                watch.ElapsedMilliseconds.ToString("N0") + "ms");
 69             Console.WriteLine("\tTime Elapsed (one time):" +
 70                (watch.ElapsedMilliseconds / iteration).ToString("N0") + "ms");
 71             Console.WriteLine("\tCPU time:\t\t" + (ticks * 100).ToString("N0")
 72                + "ns");
 73             Console.WriteLine("\tCPU time (one time):\t" + (ticks * 100 /
 74                iteration).ToString("N0") + "ns");
 75 
 76             // 5. Print GC
 77             for (int i = 0; i <= GC.MaxGeneration; i++)
 78             {
 79                 int count = GC.CollectionCount(i) - gcCounts[i];
 80                 Console.WriteLine("\tGen " + i + ": \t\t\t" + count);
 81             }
 82             Console.WriteLine();
 83         }
 84 
 85 
 86 
 87         public static void Time(string name, int iteration, IAction action)
 88         {
 89             if (String.IsNullOrEmpty(name))
 90             {
 91                 return;
 92             }
 93 
 94             if (action == null)
 95             {
 96                 return;
 97             }
 98 
 99             //1. Print name
100             ConsoleColor currentForeColor = Console.ForegroundColor;
101             Console.ForegroundColor = ConsoleColor.Yellow;
102             Console.WriteLine(name);
103 
104             // 2. Record the latest GC counts
105             //GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
106             GC.Collect(GC.MaxGeneration);
107             int[] gcCounts = new int[GC.MaxGeneration + 1];
108             for (int i = 0; i <= GC.MaxGeneration; i++)
109             {
110                 gcCounts[i] = GC.CollectionCount(i);
111             }
112 
113             // 3. Run action
114             Stopwatch watch = new Stopwatch();
115             watch.Start();
116             long ticksFst = GetCurrentThreadTimes(); //100 nanosecond one tick
117             for (int i = 0; i < iteration; i++) action.Action();
118             long ticks = GetCurrentThreadTimes() - ticksFst;
119             watch.Stop();
120 
121             // 4. Print CPU
122             Console.ForegroundColor = currentForeColor;
123             Console.WriteLine("\tTime Elapsed:\t\t" +
124                watch.ElapsedMilliseconds.ToString("N0") + "ms");
125             Console.WriteLine("\tTime Elapsed (one time):" +
126                (watch.ElapsedMilliseconds / iteration).ToString("N0") + "ms");
127             Console.WriteLine("\tCPU time:\t\t" + (ticks * 100).ToString("N0")
128                 + "ns");
129             Console.WriteLine("\tCPU time (one time):\t" + (ticks * 100 /
130                 iteration).ToString("N0") + "ns");
131 
132             // 5. Print GC
133             for (int i = 0; i <= GC.MaxGeneration; i++)
134             {
135                 int count = GC.CollectionCount(i) - gcCounts[i];
136                 Console.WriteLine("\tGen " + i + ": \t\t\t" + count);
137             }
138             Console.WriteLine();
139         }
140     }

有了上面的codeTimer我们就来测试一个吧,如字条串和并的问题,用+=还是用StringBuilder呢,有点经验的程序员肯定说是StringBuilder,是的,确实是后者,那我们就来看看这

两种方法测试的结果吧

 1      CodeTimer.Time("String  Concat", 100000,
 2                  () =>
 3                  {
 4                      var s = "1";
 5                      for (int i = 1; i < 10; i++)
 6                          s = s + "1";
 7                  });
 8 
 9       CodeTimer.Time("StringBuilder Concat", 100000,
10                () =>
11                {
12                    var s = new StringBuilder();
13                    for (int i = 1; i < 10; i++)
14                        s.Append("1");
15                });

测试的结果如下:

从图中我们可以看到StringBuilder快的很明显,无论是执行时间,还是对CPU的消耗及GC回收都远低于String的拼结,所以,才有以下结论:

在字符串拼结时,请使用StringBuilder吧!

本文转自博客园张占岭(仓储大叔)的博客,原文链接:将不确定变为确定~老赵写的CodeTimer是代码性能测试的利器,如需转载请自行联系原博主。

目录
相关文章
|
数据采集 机器学习/深度学习 大数据
行为检测代码(一):超详细介绍C3D架构训练+测试步骤
这篇文章详细介绍了C3D架构在行为检测领域的应用,包括训练和测试步骤,使用UCF101数据集进行演示。
482 1
行为检测代码(一):超详细介绍C3D架构训练+测试步骤
|
3月前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
334 1
|
4月前
|
算法 IDE Java
Java 项目实战之实际代码实现与测试调试全过程详解
本文详细讲解了Java项目的实战开发流程,涵盖项目创建、代码实现(如计算器与汉诺塔问题)、单元测试(使用JUnit)及调试技巧(如断点调试与异常排查),帮助开发者掌握从编码到测试调试的完整技能,提升Java开发实战能力。
442 0
|
2月前
|
安全 Java 测试技术
《深入理解Spring》单元测试——高质量代码的守护神
Spring测试框架提供全面的单元与集成测试支持,通过`@SpringBootTest`、`@WebMvcTest`等注解实现分层测试,结合Mockito、Testcontainers和Jacoco,保障代码质量,提升开发效率与系统稳定性。
|
3月前
|
人工智能 边缘计算 搜索推荐
AI产品测试学习路径全解析:从业务场景到代码实践
本文深入解析AI测试的核心技能与学习路径,涵盖业务理解、模型指标计算与性能测试三大阶段,助力掌握分类、推荐系统、计算机视觉等多场景测试方法,提升AI产品质量保障能力。
|
5月前
|
安全 Java 测试技术
Java 项目实战中现代技术栈下代码实现与测试调试的完整流程
本文介绍基于Java 17和Spring技术栈的现代化项目开发实践。项目采用Gradle构建工具,实现模块化DDD分层架构,结合Spring WebFlux开发响应式API,并应用Record、Sealed Class等新特性。测试策略涵盖JUnit单元测试和Testcontainers集成测试,通过JFR和OpenTelemetry实现性能监控。部署阶段采用Docker容器化和Kubernetes编排,同时展示异步处理和反应式编程的性能优化。整套方案体现了现代Java开发的最佳实践,包括代码实现、测试调试
209 0
|
6月前
|
测试技术 Go 开发者
如何为 gRPC Server 编写本地测试代码
本文介绍了如何使用 Go 语言中的 gRPC 测试工具 **bufconn**,通过内存连接实现 gRPC Server 的本地测试,避免端口冲突和外部依赖。结合示例代码,讲解了初始化内存监听、自定义拨号器及编写测试用例的完整流程,并借助断言库提升测试可读性与准确性。适用于单元及集成测试,助力高效开发。
114 1
|
机器学习/深度学习 人工智能 监控
提升软件质量的关键路径:高效测试策略与实践在软件开发的宇宙中,每一行代码都如同星辰般璀璨,而将这些星辰编织成星系的过程,则依赖于严谨而高效的测试策略。本文将引领读者探索软件测试的奥秘,揭示如何通过精心设计的测试方案,不仅提升软件的性能与稳定性,还能加速产品上市的步伐,最终实现质量与效率的双重飞跃。
在软件工程的浩瀚星海中,测试不仅是发现缺陷的放大镜,更是保障软件质量的坚固防线。本文旨在探讨一种高效且创新的软件测试策略框架,它融合了传统方法的精髓与现代技术的突破,旨在为软件开发团队提供一套系统化、可执行性强的测试指引。我们将从测试规划的起点出发,沿着测试设计、执行、反馈再到持续优化的轨迹,逐步展开论述。每一步都强调实用性与前瞻性相结合,确保测试活动能够紧跟软件开发的步伐,及时适应变化,有效应对各种挑战。
|
8月前
|
存储 jenkins 测试技术
Apipost自动化测试:零代码!3步搞定!
传统手动测试耗时低效且易遗漏,全球Top 10科技公司中90%已转向自动化测试。Apipost无需代码,三步实现全流程自动化测试,支持小白快速上手。功能涵盖接口测试、性能压测与数据驱动,并提供动态数据提取、CICD集成等优势,助力高效测试全场景覆盖。通过拖拽编排、一键CLI生成,无缝对接Jenkins、GitHub Actions,提升测试效率与准确性。
605 11