小编nb1*_*rxp的帖子

如何在C#中优化数组的复制块?

我正在编写一个实时视频成像应用程序,需要加快这种方法.它目前需要大约10毫秒才能执行,我希望将其降低到2-3毫秒.

我已经尝试了Array.Copy和Buffer.BlockCopy,它们都需要大约30毫秒,比手动副本长3倍.

一种想法是以某种方式将4个字节复制为整数,然后将它们粘贴为整数,从而将4行代码减少为一行代码.但是,我不知道该怎么做.

另一个想法是以某种方式使用指针和不安全的代码来做到这一点,但我不知道该怎么做.

非常感谢所有帮助.谢谢!

编辑:数组大小是:inputBuffer [327680],lookupTable [16384],outputBuffer [1310720]

public byte[] ApplyLookupTableToBuffer(byte[] lookupTable, ushort[] inputBuffer)
{
    System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
    sw.Start();

    // Precalculate and initialize the variables
    int lookupTableLength = lookupTable.Length;
    int bufferLength = inputBuffer.Length;
    byte[] outputBuffer = new byte[bufferLength * 4];
    int outIndex = 0;
    int curPixelValue = 0;

    // For each pixel in the input buffer...
    for (int curPixel = 0; curPixel < bufferLength; curPixel++)
    {
        outIndex = curPixel * 4;                    // Calculate the corresponding index …
Run Code Online (Sandbox Code Playgroud)

c# arrays optimization copy

16
推荐指数
1
解决办法
464
查看次数

如何在C#中快速从另一个中减去一个ushort数组?

我需要从ushort arrayB中具有相同长度的相应索引值中快速减去ushort arrayA中的每个值.

另外,如果差异为负,我需要存储零,而不是负差.

(确切地说,长度= 327680,因为我从另一个相同大小的图像中减去640x512图像).

下面的代码目前需要大约20ms,如果可能的话,我想在~5ms内将其降低.不安全的代码是可以的,但请提供一个例子,因为我不擅长编写不安全的代码.

谢谢!

public ushort[] Buffer { get; set; }

public void SubtractBackgroundFromBuffer(ushort[] backgroundBuffer)
{
    System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
    sw.Start();

    int bufferLength = Buffer.Length;

    for (int index = 0; index < bufferLength; index++)
    {
        int difference = Buffer[index] - backgroundBuffer[index];

        if (difference >= 0)
            Buffer[index] = (ushort)difference;
        else
            Buffer[index] = 0;
    }

    Debug.WriteLine("SubtractBackgroundFromBuffer(ms): " + sw.Elapsed.TotalMilliseconds.ToString("N2"));
}
Run Code Online (Sandbox Code Playgroud)

更新:虽然它不是严格意义上的C#,为了其他人的利益,我终于最终使用以下代码将C++ CLR类库添加到我的解决方案中.它运行在~3.1ms.如果使用非托管C++库,则运行时间约为2.2毫秒.由于时差很小,我决定使用托管库.

// SpeedCode.h
#pragma once
using namespace System;

namespace SpeedCode
{
    public ref class SpeedClass …
Run Code Online (Sandbox Code Playgroud)

c# arrays performance ushort subtraction

5
推荐指数
2
解决办法
1015
查看次数

标签 统计

arrays ×2

c# ×2

copy ×1

optimization ×1

performance ×1

subtraction ×1

ushort ×1