1
我試圖測量的往返時間,當我走出發送一個字節和發送另一個字節之前等待返回的字節。往返時間慢了我的申請,約15毫秒的持續,在數千個數據點。然而,當我剛剛發送的字節之前實現20毫秒的延遲,往返時間1毫秒,每20個左右樣品17毫秒之間振盪。我在代碼中做錯了什麼,導致數據傳輸效率低下並且變化很大?C#串行端口提高性能降低
EDIT .. 波特率是9600。未指定的其它值,它們是在默認值。其實我有一個具有發送和在單獨的線程接收,但我得到同樣的結果不同的代碼。我沒有在調試模式下運行。
這裏是代碼中的相關片段:
public void serserData()
{
int[] numarray = Enumerable.Range(1, 255).ToArray();//new int[] {70, 80, 90, 100, 60, 50, 40, 30 };
byte[] recvbyte = new byte[1]; //1 byte of data coming in
for (int repeat = 0; repeat <= datapoints; repeat++)
{
int rnd1 = rndseed.Next(0, numarray.Length);
sentnum = numarray[rnd1];
byte[] writebyte = new byte[] { BitConverter.GetBytes(numarray[rnd1])[0] };
Array.Reverse(writebyte);
Thread.Sleep(sleeptime);
serialPortOut.Write(writebyte, 0, 1); //Send the byte
//stopwatch.Reset();
sentelapsmil = mytimer.Duration * 1000;
while(serialPortIn.BytesToRead==0)
{
}
recvelapsmil = mytimer.Duration * 1000;
serialPortIn.Read(recvbyte, 0, 1);
int numback = BitConverter.ToInt16(new byte[] { recvbyte[0], 0x00 }, 0);
if (numback == sentnum)
{
correctbyte = 1;
}
else
{
correctbyte = 0;
}
double elapsmil = recvelapsmil - sentelapsmil;
sb.AppendLine(elapsmil + "\t " + correctbyte + "\n");
}
}
這裏是mytimer,基於QueryPerformanceCounter的
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
namespace HighResTimer
{
public class Timing
{
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out ulong lpPerformanceCount);
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out ulong lpFrequency);
public Timing()
{
if (QueryPerformanceFrequency(out freq) == false)
{
// high-performance counter not supported
//throw new Win32Exception();
}
else
{
QueryPerformanceCounter(out startTime);
}
}
private ulong startTime, curTime;
private ulong freq;
private bool started = false;
public void Start()
{
// record start time
started = true;
QueryPerformanceCounter(out startTime);
}
public double Duration
{
get
{
if (started == false) return 0;
QueryPerformanceCounter(out curTime);
return (double)(curTime - startTime)/(double)freq;
}
}
public ulong GetStartCode()
{
return startTime;
}
public ulong GetFrequency()
{
return freq;
}
}
}
什麼是mytimer?它有多準確?你在調試中運行嗎?爲什麼你的讀代碼和寫代碼在同一個線程上(理想的情況是它會在發送字節之前等待接收)。你使用什麼波特率,停止位等? –
這裏有一些有趣的信息:https://social.msdn.microsoft.com/Forums/vstudio/en-US/e36193cd-a708-42b3-86b7-adff82b19e5e/how-does-serialport-handle-datareceived?forum=netfxbcl – PaulF
我已經更新了我的問題,並回答了評論中的一些問題。 – nt387