【问题标题】:best way to check performance of the code in C# [duplicate]在 C# 中检查代码性能的最佳方法 [重复]
【发布时间】:2014-09-03 06:19:09
【问题描述】:

我们正在开发两个不同的库,它们往往执行相同的工作。我被指派检查哪个库在给定的输入集下更快地执行相同的工作。有多个测试用例可以确定这一点,我想检查库执行任务花费了多少时间(以毫秒为单位)。

以下是代码大纲。

// preparation of input parameters
// Get the timestamp
// Calling the desired library with the set of input parameters
// again get the timestamp
// Process the output received from the library

// get a diff between timestamp and write it into a file.

我应该用 C# 来做,在阅读一些提供的文档和一些在线搜索时,我想出了以下代码,可用于测量所花费的时间(以毫秒为单位)

int s1 = DateTime.Now.Millisecond;
int e1 = DateTime.Now.Millisecond;
int f1 = e1 - s1;
FileStream fs = new FileStream("Time_Diff.txt", FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
string str = Convert.ToString(f1);
sw.WriteLine(str);
sw.WriteLine(e1 + " " + s1);
sw.Flush();
sw.Close();

我只是想知道我正朝着正确的方向前进。另外,是否有人可以建议我做同样事情的另一种方法?

我想知道的另一件事是我可以使用哪些其他实用方法来确保我们选择的库能够提供最佳性能?

另一个小请求。有人可以告诉我如何实现秒表(或任何其他类似的方式来获取时间戳)在 C++ 中做同样的事情吗?

谢谢, 阿齐姆

【问题讨论】:

  • DateTime-instances 之间的差异不是一个好主意,因为精度不是那么好 (jaychapman.blogspot.co.at/2007/11/datetimenow-precision.html) ... 使用 Stopwatch-instance!无论如何,只需使用关键字“benchmark”和“c#”进行复杂的谷歌搜索......或者,只需在 SO 上阅读以下问题:stackoverflow.com/questions/28637/…
  • 使用Stopwatch 类而不是DateTimeRelated question.
  • 每次通话需要多长时间?您应该确保为大量工作安排时间 - 这可能意味着要花费数千或数百万次通话。
  • 哦,使用File.AppendAllText - 或者如果你必须使用StreamStreamWriter,使用using语句:)
  • 感谢大家的帮助!!!使用秒表实现。

标签: c# c++ performance


【解决方案1】:

如下使用秒表。

        var stopWatch = System.Diagnostics.Stopwatch.StartNew();
        FileStream fs = new FileStream("Time_Diff.txt", FileMode.Append);
        StreamWriter sw = new StreamWriter(fs);
        //Total time required
        sw.WriteLine("\nTotal time: " + stopWatch.Elapsed.TotalSeconds.ToString());
        sw.Flush();
        sw.Close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2013-02-21
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多