gpt4 book ai didi

c# - 我如何计算使用 DateTime.Now 调用该方法的速度?

转载 作者:行者123 更新时间:2023-11-30 19:25:16 26 4
gpt4 key购买 nike

我将给出方法代码的顶部,因为整个代码很长,在这种情况下不需要。

static int tickCountLength = 1000;
int[] tickCounts = new int[tickCountLength];
int numberOfTicks = 0;
TimeSpan dtn;

void DoCaptureRenderTarget(Device device, string hook)
{
//Environment.TickCount-->array

tickCounts[numberOfTicks] = Environment.TickCount;
numberOfTicks++;

DateTime start1 = DateTime.Now;
DateTime end1 = DateTime.Now;
this.DebugMessage("Capture Time Testing " + (end1 - start1).ToString());
dtn = end1 - start1;
if (dtn.Seconds > 0)
{
string fffff = "fgf";
}
if (numberOfTicks >= tickCountLength)
{

StreamWriter w = new StreamWriter(@"c:\Milliseconds\TickCount.txt", true);
foreach (int tick in tickCounts)
{
w.WriteLine("TickCount === > " + tick.ToString());

}
w.Close();
numberOfTicks = 0;
}

该方法每 1 毫秒或 20 毫秒调用一次,不确定实时时间。所以我添加了这部分试图计算:

DateTime start1 = DateTime.Now;
DateTime end1 = DateTime.Now;
this.DebugMessage("Capture Time Testing " + (end1 - start1).ToString());
dtn = end1 - start1;
if (dtn.Seconds > 0)
{
string fffff = "fgf";
}

但这肯定是错误的,end1 和 start1 之间的时间是 00:00:00:00我如何以毫秒为单位计算方法每次调用的时间?

也许:每次都使用 DateTime.Now.Millisecond 并手动从前一个中减去(通过查看)?不知道该怎么做。

最佳答案

使用StopWatch

例子:

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);// or whatever code you want to calculate elapsed time.
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;

// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);

关于c# - 我如何计算使用 DateTime.Now 调用该方法的速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29915073/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com