如何使这个大C#循环更快?

时间:2019-02-21 07:45:11

标签: c# performance for-loop

下面的代码使用了一个完整的内核性能,它花10到12秒才能完成,这很慢,我怎样才能使其更快?

NetworkStream networkStream = (NetworkStream)param;
byte[] sendBytes = new byte[1000000];
int current = 0;
int cpos = 0;
for (int i = 0; i < 16; i++)
{
    for (int j = 0; j < 16; j++)
    {
       for (int k = 0; k < 16; k++)
       {
          sendBytes[current] = i;
          current++;
          sendBytes[current] = j;
          current++;
          sendBytes[current] = k;
          current++;
          for (int x = 0; x < 16; x++)
          {
              for (int y = 0; y < 16; y++)
              {
                  for (int z = 0; z < 16; z++)
                  {
                      sendBytes[current] = getItem(x + i * 16, y + j * 16, z + k * 16);
                      current++;
                  }
              }
          }
          //Here it also copies the old bytes and compresses them using zlibstream
          networkStream.Write(sendBytes, 0, current);
          current = 0;
      }
   }
}
byte getItem(int x, int y, int z)
{
   return blockIds[x, y, z];
}

编辑:添加了缺少的方法代码。

1 个答案:

答案 0 :(得分:1)

  

请注意,发送已保存的内容仅需0.1秒

我想这是对NetworkStream.Write方法的1次调用的持续时间

通过将数据发送到环回进行的简单测试。在我的PC上花费大约300毫秒,在不发送数据的情况下花费50毫秒。显然,原因在于您的网络速度。

循环足够快

//Local server
Socket server = new Socket(SocketType.Stream, ProtocolType.Tcp);
Socket peer = null;
server.Bind(new IPEndPoint(IPAddress.Any, 29999));
server.Listen(50);
server.BeginAccept(ar =>
{
    peer = server.EndAccept(ar);
    byte[] buf = new byte[16 * 16 * 16 + 3];
    while (peer.Connected)
        peer.Receive(buf);
},
null);

//Client
Socket client = new Socket(SocketType.Stream, ProtocolType.Tcp);
client.Connect(new IPEndPoint(IPAddress.Loopback, 29999));
var networkStream = new NetworkStream(client);

//Loop
byte[] sendBytes = new byte[16 * 16 * 16 + 3];
int current = 0;
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 16; i++)
    for (int j = 0; j < 16; j++)
        for (int k = 0; k < 16; k++)
        {
            sendBytes[current++] = (byte)i;
            sendBytes[current++] = (byte)j;
            sendBytes[current++] = (byte)k;

            for (int x = 0; x < 16; x++)
                for (int y = 0; y < 16; y++)
                    for (int z = 0; z < 16; z++)
                        sendBytes[current++] = getItem(x + i * 16, y + j * 16, z + k * 16);

            networkStream.Write(sendBytes, 0, current);
            current = 0;
        }
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

//Clean works
client.Close();
peer.Close();
server.Close();