c# library 之 代码库

本文介绍了一种使用System.Diagnostics.Stopwatch进行代码性能测试的方法,展示了如何测量文件读取时间。此外,深入探讨了多种键值对数据排序策略,包括使用SortedDictionary、Linq查询及自定义扩展方法实现升序与降序排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要测试时间的代码
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();//  开始监视代码运行时间
#region
需要测试的代码
#endregion
stopwatch.Stop();//  停止监视
TimeSpan timeSpan = stopwatch.Elapsed;//  获取当前实例测量得出的总时间
double seconds = timeSpan.TotalSeconds;
Console.WriteLine("文件读取的总秒数为:{0}", seconds);
键值对数据排序
//1.使用排序字典,默认只支持升序 
SortedDictionary<DateTime, String> dd = new SortedDictionary<DateTime, String>(); 
DateTime dt = DateTime.Now; 
dd.Add(dt, "bbb"); 
dd.Add(dt.AddDays(-1), "ccc"); 
dd.Add(dt.AddDays(1), "aaa"); 
//可以借助List得到降序键或值 
List<String> lst = new List<String>(dd.Values); 
lst.Reverse(); 
//2使用Linq查询 
Dictionary<DateTime, String> dd = new Dictionary<DateTime, String>(); 
DateTime dt = DateTime.Now; 
dd.Add(dt, "bbb"); 
dd.Add(dt.AddDays(-1), "ccc"); 
dd.Add(dt.AddDays(1), "aaa"); 
 
var result = from pair in dd orderby pair.Key descending select pair; 
List<String> lst = new List<String>(); 
foreach (var kv in result) 
{ 
    lst.Add(kv.Value); 
} 
//或 
Dictionary<DateTime, String> dd2 = result.ToDictionary(p=>p.Key, p=>p.Value); 
//3.使用扩展方法  
Dictionary<DateTime, String> dd = new Dictionary<DateTime, String>();  
DateTime dt = DateTime.Now;  
dd.Add(dt, "bbb");  
dd.Add(dt.AddDays(-1), "ccc");  
dd.Add(dt.AddDays(1), "aaa");  
  
Dictionary<DateTime, String> dicAsc = dd.OrderBy(p=>p.Key).ToDictionary(p=>p.Key, p=>p.Value);  
Dictionary<DateTime, String> dicDesc = dd.OrderByDescending(p=>p.Key).ToDictionary(p=>p.Key, p=>p.Value);
文件读写
//写
StreamWriter log = new StreamWriter(@"E:\wli\send.txt");
//重点是FileAccess为写入模式。
FileStream fsw = new FileStream(@"E:\wli\tmp.zip", FileMode.OpenOrCreate,FileAccess.Write);
//读
FileStream fs = new FileStream(@"E:\wli\mdl_3_4_0.zip", FileMode.OpenOrCreate);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

R助手

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值