【发布时间】:2016-01-04 17:08:44
【问题描述】:
我需要通过发送命令然后读取结果,在 X 分钟内尽可能快地连续检索数据。我不确定以下代码是否有效或用于不断检索:
DateTime utcStartTime = DateTime.UtcNow;
while (DateTime.UtcNow <= (utcStartTime.AddSeconds(recordTime))) //Run the read-write function for approximately the time specified
{
try
{
Write("Write.Request"); //Requests the data
Pmeas = Read(); //Reads the returned string. String = "ReadError" if no result is found.
//Note that the following error checker doesn't effect the speed of data collection at a millisecond level (already checked), and is therefore not the cause of any delay.
if (String.IsNullOrEmpty(Pmeas))
{
Pmeas = "ReadError"; //Necessary due to an apparent overwrite caused by the read function - Tells the later output (outside of while loop) that Pmeas experienced a read error
DateTime utcTime = DateTime.UtcNow; //Get the current time in UTC seconds (may need correcting).
pArray[i] = (Pmeas + "\t" + utcTime.ToString("%d") + Environment.NewLine); //Appends the Pmeas of each instance to a string array with a timestamp
}
else
{
DateTime utcTime = DateTime.UtcNow;
pArray[i] = (Pmeas + "\t" + utcTime.ToString("%d") + Environment.NewLine); //Appends the Pmeas of each instance to a string array with a timestamp
}
Pmeas = "ReadError"; //Reset Pmeas to prove in file that Pmeas experienced a read error
}
catch (Exception f) //Catch an exception if try fails
{
Console.WriteLine("{0} Exception caught.", f);
}
i++; //let i grow so that the array can also grow, plus have a variable already available for being having the string being written into a file (not part of question or code-in-question).
}
请注意,所有变量,如 i、Pmeas 和 pArray 都是在循环之前预定义的(以防止错误),并且 UTC 应该以秒为单位(不确定当前的语法;具有十进制精度)。正如我所说,我正在寻找一种方法,该方法可以使用上面给出的读取和写入函数不断地从另一个来源收集数据,并在一段时间内不断地这样做而不会延迟。我的简单问题是,这是收集数据的正确方法还是有更好和/或更有效的方法?
欢迎对代码的所有输入,即使它没有完整回答问题。
【问题讨论】:
-
Write和Read实际需要多长时间?上面发布的代码是否真的会导致可量化的速度问题 - 例如,如果这些方法比你包裹它们的代码慢一个数量级(例如),我不会担心...... -
上面的当前代码(最初是在 for 循环中)有 17 毫秒的延迟。我们正试图将其降低到至少一半,但我们仍然需要每个数据点的时间戳。
-
@Midimistro 如果你想达到这个目标,你需要知道哪些代码行占用了这 17 毫秒的大部分时间,如果没有分析器,你就无法做到这一点。此外,DateTime 仅精确到大约 15 毫秒,要低于您需要切换到 Stopwatch,在开始时记录一个 DateTime,然后使用秒表计算已经过去了多少时间。当你去写你的输出时,从数据点的记录开始时间+时间跨度。
标签: c# loops datetime time constants