码迷,mamicode.com
首页 > Windows程序 > 详细

C# 计时函数(毫秒)

时间:2018-04-28 16:59:09      阅读:326      评论:0      收藏:0      [点我收藏+]

标签:col   变量   val   star   system   ice   dia   service   int   

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

class Program
{
    //调用API函数
    [DllImport("kernel32.dll")]
    extern static short QueryPerformanceCounter(ref long x);
    [DllImport("kernel32.dll")]
    extern static short QueryPerformanceFrequency(ref long x);

    static void Main(string[] args)
    {
        // 方法一
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        Thread.Sleep(1000);
        stopWatch.Stop();
        long times1 = stopWatch.ElapsedMilliseconds; 
        Console.WriteLine("RunTime " + times1);


        // 方法二
        long stop_Value = 0;
        long start_Value = 0;
        long freq = 0;
        QueryPerformanceFrequency(ref freq);  //获取CPU频率

        QueryPerformanceCounter(ref start_Value); //获取初始前值
        Thread.Sleep(1000);
        QueryPerformanceCounter(ref stop_Value);//获取终止变量值
        var times2 = (stop_Value - start_Value) / (double)freq * 1000;
        Console.WriteLine("RunTime " + times2);
    }
}

 

C# 计时函数(毫秒)

标签:col   变量   val   star   system   ice   dia   service   int   

原文地址:https://www.cnblogs.com/LicwStack/p/8968361.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!