您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

用C#描述数据结构1:统计代码执行时间对象的代码详解

2024/5/28 20:49:19发布20次查看
自定义一个统计代码执行时间的类calctiming,考虑了:
在统计执行过程中,不允许有垃圾回收。即在统计代码执行时间之前,就让gc完成垃圾回收。
确保统计的是当前进程中代码的执行时间。
编写代码如下:
public class calctiming { timespan starttime; private timespan endtime; timespan duration; public calctiming() { starttime = new timespan(0); duration = new timespan(0); } public void starttime() { //强制对所有代进行垃圾回收 gc.collect(); //挂起线程,终结器线程清空该队列为止 gc.waitforpendingfinalizers(); //用户运行代码的起始时间 starttime = process.getcurrentprocess().userprocessortime; } //统计的代码执行完毕的时间 public void stoptime() { endtime = process.getcurrentprocess().userprocessortime; duration = endtime.subtract(starttime); } //返回统计的代码执行消耗的时间 public timespan result() { return duration; } }
运用以上calctiming类,统计显示数组的消耗时间:
class program { static void main(string[] args) { int[] nums = new int[100000]; buildarray(nums); calctiming calctime= new calctiming(); calctime.starttime(); displaynums(nums); calctime.stoptime(); console.writeline(string.format("共用时间:{0} ms",calctime.result().totalmilliseconds)); console.read(); } static void buildarray(int[] arr) { for (int i = 0; i < 100000; i++) arr[i] = 1; } static void displaynums(int[] arr) { for (int i = 0; i <= arr.getupperbound(0); i++) console.write(arr[i] + " "); } }
总结,在接下来用c#描述所有数据结构,统计消耗的时间时,采用calctiming对象。
以上就是用c#描述数据结构1:统计代码执行时间对象的代码详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product