c#stopwatch.startnew()始终返回0

c#stopwatch.startnew()始终返回0,c#,stopwatch,C#,Stopwatch,我有一个回路,我想测量速度: private static string[] sequentialTest(string[] thisstringlist) { var watch = Stopwatch.StartNew(); string[] returnList = new string[2150]; for (int i = 0; i < thisstringlist.Length; ++i)

我有一个回路,我想测量速度:

        private static string[] sequentialTest(string[] thisstringlist)
    {
        var watch = Stopwatch.StartNew();

        string[] returnList = new string[2150];
        for (int i = 0; i < thisstringlist.Length; ++i)
        {
            int thisI = i;
            returnList[i] = thisstringlist[i] + "pluuus this";
        }
        int thiss = 0;

        var elapsedMs = watch.ElapsedMilliseconds;
        Console.WriteLine("execution time" + watch.ElapsedMilliseconds);

        return returnList;

    }
私有静态字符串[]顺序测试(字符串[]thisstringlist)
{
var watch=Stopwatch.StartNew();
字符串[]返回列表=新字符串[2150];
对于(int i=0;i
应该很简单,秒表应该只测量这个操作需要多长时间,但我一直返回0


我还尝试插入thread.sleep(),只是为了迫使代码花费一些时间,但这也不起作用,正如名称所示,需要停止秒表才能看到所有这些值,如文档中所示。为了解决这个问题,编写
watch.Stop()之前
var elapsedMs=watch.elapsedmillesons

注意:在较新版本的.NET framework中,不需要
停止

另外,检查私有静态字符串[]顺序测试(字符串[]thisstringlist) { 秒表秒表=新秒表(); 秒表。开始(); 字符串[]返回列表=新字符串[2150]; 对于(int i=0;i
这个StringList有多大?通过中断指向方法,向自己证明它(它返回0)。我怀疑这是BLC中的错误,更可能只是你的假设。最后一点,这不是一种对代码进行基准测试的好方法。使用基准框架列表比2000个元素稍大一点,你认为是哪一种假设?我认为该方法运行时间为亚毫秒,在其中放置一个
线程。Sleep(100)
来证明它,或者断点itah,是的。但是当我添加线程时,它会起作用吗?sleep(5000)?您可以尝试使用ElapsedTicks而不是ElapsedMilliseconds来查看是否工作正常。嗯“您可以在秒表实例运行或停止时查询“已用”、“ElapsedMilliseconds”和“ElapsedTicks”属性。秒表运行时,经过时间属性稳步增加;当实例停止时,它们保持不变。“非常感谢,这很有效,即使循环仍然是子循环milliseconds@MichaelRandall好看!问题是,据我所知,这是一个新功能,因为我在过去使用秒表时遇到了同样的问题。也是为了一致性(为了不考虑帐户打印速度,尽管它们很小),最好停止手表imho@s3j80如果我提供了帮助,请注明这是正确答案(同样如上所述,您可以在更新的.net framework上编写)@ho4upivo请更正您的答案。
stop
不需要。这会让未来的用户感到困惑。为什么要在方法之外声明秒表?没有好处,但如果(或当)多线程进入图片中,您会遇到麻烦
 private static string[] sequentialTest(string[] thisstringlist)
    {
     Stopwatch stopwatch = new Stopwatch();
      stopwatch.Start();
      string[] returnList = new string[2150];
        for (int i = 0; i < thisstringlist.Length; ++i)
        {
            int thisI = i;
            returnList[i] = thisstringlist[i] + "pluuus this";
        }
        int thiss = 0;
       Console.WriteLine("execution time" + stopwatch.Elapsed.TotalMilliseconds);
      stopwatch.Stop();
   }