.NET Framework Bookmark and Share   
 index > .NET Base Class Library > how to record cpu time
 

how to record cpu time

hello,
i am trying to see how a method in my application does in terms of cpu usage. i have used performancecounter class objects to get the %values of the cpu usages, but dont know how to get the time the cpu takes to execute my method.

if you have any ideas, please let me know
thanks

m_3899970

The easiest thing you can do it to use StopWatch class in System.Diagnostics...

Call its method Start before calling that function and call Stop method right after the ending line of function.

It'll give you what you want i.e result in Miliseonds, CPU Ticks using ElapsedTicks, or ElapsedMiliseconds properties....

I hope this will help!

Best Regards,

rizwan.

RizwanSharp
You can mesure the time using date variables where you can set the first variable to DateTime.Now and the second also the same, and then substract those dates and get passed time for executing method. There is also another way, to mesure CPU ticks needed to execute your method. Here is a class for that:
public class PerfTimer
{
   [
DllImport("Kernel32.dll"
)]
   public static extern void QueryPerformanceCounter(ref long
ticks);

   private
long startTime = 0;
   private long
stopTime = 0;

   public void Start()
   {
      QueryPerformanceCounter(
ref
startTime);
   }
  

   public void Stop()
   {
      QueryPerformanceCounter(
ref
stopTime);
   }

   public long Time
   {
      get { return
stopTime - startTime; }
   }
}

You will invoke start method before the start of the method and stop after finishing method. And then you will have CPU ticks needed to finish the method. Here is an exaple how to do that:
Int64 ticks = 0;
perfTimer.Start();
YourMethod
();  //execute your method
perfTimer.Stop();

ticks = perfTimer.Time;

Debug.WriteLine("ticks: " + ticks);

QueryPerformanceCounter uses CPU clock timer and that's way is more accurate. But be aware that doesn't works properly on all processors, for example Athlon64.

boban.s

The easiest thing you can do it to use StopWatch class in System.Diagnostics...

Call its method Start before calling that function and call Stop method right after the ending line of function.

It'll give you what you want i.e result in Miliseonds, CPU Ticks using ElapsedTicks, or ElapsedMiliseconds properties....

I hope this will help!

Best Regards,

rizwan.

RizwanSharp

You can use google to search for other answers

Custom Search

More Threads

• Create objects from a string
• creating an OLE DB provider in .NET
• Type.GetMethods() can't find some methods?
• How to convert a word from one language into another language?
• Session - Last Accessed Time
• Screen Saver notifications
• How to get the value of: MyObject.Property1 by name. Use reflection?
• Philosophical question
• How to create intellisense
• OutOfMemoryException in DrawImage with ImageAttributes