I want to measure the time that a C# routine needs. Because there are many other threads I only want to count the time of this one thread. In Java I can use getCurrentThreadCpuTime
.
How can I do it?
I want to measure the time that a C# routine needs. Because there are many other threads I only want to count the time of this one thread. In Java I can use getCurrentThreadCpuTime
.
How can I do it?
You should look into PerformanceCounters. They are quite complex and can be a bit of a pain to set up, but are robust in what they offer for metrics. A couple of things that might help:
You can't. You cannot measure the accumulated time ON THE CPU for a particular thread
.
The most accurate thing you could do would be to spin off a separate process
for each of your tasks, and then measure the CPU time for the process (which actually can be done in .Net)... but that's overkill.
If you need help on how to do that, you should ask another question specifically for that.
You can use Stopwatch for that. It would be the simplest way to get that.
public void Worker()
{
var stopwatch = new Stopwatch();
stopwatch.Start();
///Do your wwork here
var timeElapsed = stopwatch.Elapsed;
}
UPDATE
I got your question wrong, so what about this? It does not work if you use thread sleep. Sorry if this still is not what you're looking for.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using System.Collections.Concurrent;
namespace ConsoleApplication2
{
class Program
{
static ConcurrentDictionary<int, ProcessThread> threadIdsMapping = new ConcurrentDictionary<int, ProcessThread>();
static void Main(string[] args)
{
Thread oThread = new Thread(
delegate()
{
threadIdsMapping.GetOrAdd(Thread.CurrentThread.ManagedThreadId, GetProcessThreadFromWin32ThreadId(null));
long counter = 1;
while (counter < 1000000000)
{
counter++;
}
});
oThread.Start();
oThread.Join();
Console.WriteLine(threadIdsMapping[oThread.ManagedThreadId].TotalProcessorTime);
Console.WriteLine(threadIdsMapping[oThread.ManagedThreadId].UserProcessorTime);
Console.WriteLine(DateTime.Now - threadIdsMapping[oThread.ManagedThreadId].StartTime);
Console.ReadKey();
}
public static ProcessThread GetProcessThreadFromWin32ThreadId(int? threadId)
{
if (!threadId.HasValue)
{
threadId = GetCurrentWin32ThreadId();
}
foreach (Process process in Process.GetProcesses())
{
foreach (ProcessThread processThread in process.Threads)
{
if (processThread.Id == threadId) return processThread;
}
}
throw new Exception();
}
[DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]
public static extern Int32 GetCurrentWin32ThreadId();
}
}