第一种方法利用System.DateTime.Now:
1
2
3
4
5
6
7
8
9
10
|
static
void
SubTest()
{
DateTime beforDT = System.DateTime.Now;
//耗时巨大的代码
DateTime afterDT = System.DateTime.Now;
TimeSpan ts = afterDT.Subtract(beforDT);
Console.WriteLine(
"DateTime总共花费{0}ms."
, ts.TotalMilliseconds);
}
|
第二种用Stopwatch类(System.Diagnostics):
1
2
3
4
5
6
7
8
9
10
11
|
static
void
SubTest()
{
Stopwatch sw =
new
Stopwatch();
sw.Start();
//耗时巨大的代码
sw.Stop();
TimeSpan ts2 = sw.Elapsed;
Console.WriteLine(
"Stopwatch总共花费{0}ms."
, ts2.TotalMilliseconds);
}
|
第三种用API实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
[System.Runtime.InteropServices.DllImport(
"Kernel32.dll"
)]
static
extern
bool
QueryPerformanceCounter(
ref
long
count);
[System.Runtime.InteropServices.DllImport(
"Kernel32.dll"
)]
static
extern
bool
QueryPerformanceFrequency(
ref
long
count);
static
void
SubTest()
{
long
count = 0;
long
count1 = 0;
long
freq = 0;
double
result = 0;
QueryPerformanceFrequency(
ref
freq);
QueryPerformanceCounter(
ref
count);
//耗时巨大的代码
QueryPerformanceCounter(
ref
count1);
count = count1 - count;
result = (
double
)(count) / (
double
)freq;
Console.WriteLine(
"QueryPerformanceCounter耗时: {0} 秒"
, result);
}
|
【推荐】腾讯云新用户域名抢购1元起,抓紧抢购
· 阮一峰:加密货币的本质
· ofo被曝订单较峰值跌六成 账户现金仅能支撑一个月
· 途牛宣布一亿美元股票回购计划及CTO任命
· 我们帮你划了一份微信公开课PRO的重点
· iPhone 4S起死回生,可降级至iOS 6.1.3
» 更多新闻...
· 以操作系统的角度述说线程与进程
· 软件测试转型之路
· 门内门外看招聘
· 大道至简,职场上做人做事做管理
2015-03-15 WinForm编程数据视图之DataGridView浅析