Hor*_*ux7 8 c# performance multithreading
我想测量一下C#例程所需的时间.因为还有很多其他线程我只想计算这一个线程的时间.在Java中我可以使用getCurrentThreadCpuTime.
我该怎么做?
MeT*_*tus -3
您可以使用秒表来实现这一点。这将是实现这一目标的最简单方法。
public void Worker()
{
var stopwatch = new Stopwatch();
stopwatch.Start();
///Do your wwork here
var timeElapsed = stopwatch.Elapsed;
}
Run Code Online (Sandbox Code Playgroud)
更新
我把你的问题问错了,那这个呢?如果使用线程睡眠则不起作用。很抱歉,如果这仍然不是您想要的。
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
827 次 |
| 最近记录: |