【发布时间】:2011-01-05 13:17:29
【问题描述】:
我正在尝试确定哪种删除字符串的方法是最快的。
我只是获取开始和结束时间并显示差异。
但结果是如此多种多样,例如如下所示,相同的方法可能需要 60 毫秒到 231 毫秒。
有什么更好的方法可以获得更准确的结果?
alt text http://www.deviantsart.com/upload/1q4t3rl.png
using System;
using System.Collections;
using System.Collections.Generic;
namespace TestRemoveFast
{
class Program
{
static void Main(string[] args)
{
for (int j = 0; j < 10; j++)
{
string newone = "";
List<string> tests = new List<string>();
for (int i = 0; i < 100000; i++)
{
tests.Add("{http://company.com/Services/Types}ModifiedAt");
}
DateTime start = DateTime.Now;
foreach (var test in tests)
{
//newone = ((System.Xml.Linq.XName)"{http://company.com/Services/Types}ModifiedAt").LocalName;
newone = Clean(test);
}
Console.WriteLine(newone);
DateTime end = DateTime.Now;
TimeSpan duration = end - start;
Console.WriteLine(duration.ToString());
}
Console.ReadLine();
}
static string Clean(string line)
{
int pos = line.LastIndexOf('}');
if (pos > 0)
return line.Substring(pos + 1, line.Length - pos - 1);
//return line.Substring(pos + 1);
else
return line;
}
}
}
【问题讨论】:
-
我不认为测量本身有任何不准确之处。你可能的意思是,没想到会有这么大的分散。我想您必须确保计算机上没有其他程序正在使用您所有的 cpu 时间或内存。
-
请注意,由 DateTime 测量的“挂钟时间”仅精确到 30 毫秒。 DateTime 用于表示墙上的时钟或您上次编辑文件的时间;它不必具有纳秒级精度,所以它没有。
标签: c# performance