C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#计算程序运行时间

C#计算一段程序运行时间的多种方法总结

作者:xzjxylophone

这篇文章主要为大家详细介绍了C#计算一段程序运行时间的多种方法,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以了解下

直接代码:

第一种方法利用System.DateTime.Now

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)

static void SubTest()
{
	Stopwatch sw = new Stopwatch();
	sw.Start();
  
	//耗时巨大的代码
	
	sw.Stop();
	TimeSpan ts2 = sw.Elapsed;
	Console.WriteLine("Stopwatch总共花费{0}ms.", ts2.TotalMilliseconds);
}

第三种用API实现: 

[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);
}

方法补充

C#中获取程序执行时间的三种方法

1. 使用DateTime类

你可以在程序开始执行前获取当前时间,然后在程序结束时再次获取当前时间,通过这两个时间点计算程序执行时间。

using System;
 
class Program
{
    static void Main()
    {
        DateTime startTime = DateTime.Now;
 
        // 执行你的代码
        for (int i = 0; i < 1000000; i++)
        {
            // 示例:一个简单的循环
        }
 
        DateTime endTime = DateTime.Now;
        TimeSpan executionTime = endTime - startTime;
 
        Console.WriteLine("程序执行时间: " + executionTime.TotalMilliseconds + " 毫秒");
    }
}

2. 使用Stopwatch类

System.Diagnostics.Stopwatch类是测量时间的一种更精确的方法,特别是对于需要高精度计时的场景。

using System;
using System.Diagnostics;
 
class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
 
        // 执行你的代码
        for (int i = 0; i < 1000000; i++)
        {
            // 示例:一个简单的循环
        }
 
        stopwatch.Stop();
        Console.WriteLine("程序执行时间: " + stopwatch.ElapsedMilliseconds + " 毫秒");
    }
}

3. 使用Environment.TickCount或Environment.TickCount64(对于64位系统)

这种方法不如Stopwatch精确,但对于简单的性能测试或快速获取时间差也是可行的。

using System;
 
class Program
{
    static void Main()
    {
        int startTime = Environment.TickCount; // 或使用Environment.TickCount64对于64位系统以避免溢出
 
        // 执行你的代码
        for (int i = 0; i < 1000000; i++)
        {
            // 示例:一个简单的循环
        }
 
        int endTime = Environment.TickCount; // 或使用Environment.TickCount64对于64位系统以避免溢出
        int executionTime = endTime - startTime; // 注意:这将返回以毫秒为单位的整数,但不直接提供TimeSpan对象。
 
        Console.WriteLine("程序执行时间: " + executionTime + " 毫秒");
    }
}

到此这篇关于C#计算一段程序运行时间的多种方法总结的文章就介绍到这了,更多相关C#计算程序运行时间内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文