C#记录执行毫秒!

C#记录执行毫秒--很不错

 

using  System;
using  System.Runtime.InteropServices;
using  System.ComponentModel;
using  System.Threading;


 
internal   class  HiPerfTimer
  {
   [DllImport(
" Kernel32.dll " )]
   
private   static   extern   bool  QueryPerformanceCounter(
    
out   long  lpPerformanceCount);

   [DllImport(
" Kernel32.dll " )]
   
private   static   extern   bool  QueryPerformanceFrequency(
    
out   long  lpFrequency);

   
private   long  startTime, stopTime;
   
private   long  freq;

   
//  Constructor
    public  HiPerfTimer()
   {
    startTime 
=   0 ;
    stopTime  
=   0 ;

    
if  (QueryPerformanceFrequency( out  freq)  ==   false )
    {
     
//  high-performance counter not supported
      throw   new  Win32Exception();
    }
   }

   
//  Start the timer
    public   void  Start()
   {
    
//  lets do the waiting threads there work
    Thread.Sleep( 0 );

    QueryPerformanceCounter(
out  startTime);
   }

   
//  Stop the timer
    public   void  Stop()
   {
    QueryPerformanceCounter(
out  stopTime);
   }

   
//  Returns the duration of the timer (in seconds)
    public   double  Duration
   {
    
get
    {
     
return  ( double )(stopTime  -  startTime)  /  ( double ) freq;
    }
   }
  }

 } 
C#执行CPUID指令通常需要使用平台调用(P/Invoke)功能来调用操作系统提供的底层接口。CPUID指令是x86架构处理器提供的一条指令,用于获取处理器的特定信息。为了记录执行此指令耗费的时间,可以使用C#的Stopwatch类。以下是实现的步骤和示例代码: 1. 使用`System.Runtime.InteropServices`命名空间中的`DllImport`属性来声明一个外部方法,这个方法将调用Windows平台的`__cpuid`函。 2. 使用`System.Diagnostics`命名空间中的`Stopwatch`类来测量时间。 示例代码如下: ```csharp using System; using System.Runtime.InteropServices; using System.Diagnostics; class Program { // 声明外部方法,调用Windows的__cpuid函 [DllImport("libc")] private static extern unsafe void __cpuid(int* CPUInfo, int InfoType); static void Main() { // 使用Stopwatch测量执行时间 Stopwatch stopwatch = Stopwatch.StartNew(); // 定义一个足够大的组来接收CPUID的结果 int[] CPUInfo = new int[4]; // 执行CPUID指令,例如获取处理器的特征信息(EAX=1) unsafe { fixed (int* infoPtr = CPUInfo) { __cpuid(infoPtr, 1); } } // 停止计时器 stopwatch.Stop(); // 输出结果和执行时间 Console.WriteLine("CPUID 执行结果: " + string.Join(", ", CPUInfo)); Console.WriteLine("CPUID 执行耗时: " + stopwatch.ElapsedMilliseconds + " 毫秒"); } } ``` 请注意,示例代码中的`__cpuid`函实际上并不是标准Windows API的一部分,通常你需要链接到一个专门的C/C++库或者使用其他方法来执行CPUID指令。在某些平台上(如非Windows),可能需要其他方式来执行这一指令。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值