Here are the examples of the csharp api System.Threading.Tasks.Parallel.For(long, long, System.Threading.Tasks.ParallelOptions, System.Func, System.Func, System.Action) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
960 Examples
19
View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne
License : GNU General Public License v3.0
Project Creator : 1RedOne
private async void CreateClientsButton_Click(object sender, RoutedEventArgs e)
{
DeviceExpander.IsExpanded = true;
string BaseName = NewClientName.Text;
int CountOfMachines = (Int32.TryParse(NumberOfClients.Text, out int unUsed)) ? Int32.Parse(NumberOfClients.Text) : 1;
int BeginningWith = (!StartingNumber.Text.Length.Equals(0)) ? Int32.Parse(StartingNumber.Text) : 0;
List<String> DeviceList = new List<string>();
int current = 0;
object lockCurrent = new object();
var progress = new Progress<int>(_ => IdCounter++) as IProgress<int>;
for (int i = BeginningWith; i <= CountOfMachines; i++)
{
string ThisClient = BaseName + i;
DeviceList.Add(ThisClient);
}
var myTask = Task.Run(() =>
{
Parallel.For(0, DeviceList.Count,
new ParallelOptions { MaxDegreeOfParallelism = MaxThreads },
(ii, loopState) =>
{
int thisCurrent = 0;
lock (lockCurrent)
{
thisCurrent = current;
current++;
}
string device = DeviceList[thisCurrent];
Device ThisDevice = new Device() { Name = device, Status = "Starting...", ImageSource = "Images\\step01.png", ProcessProgress = 10 };
Devices.Add(ThisDevice);
int thisIndex = Devices.IndexOf(ThisDevice);
RegisterClient(thisIndex);
progress.Report(0);
});
});
await myTask;
}
19
View Source File : CloudPolygonCrop.cs
License : GNU Lesser General Public License v3.0
Project Creator : 9and3
License : GNU Lesser General Public License v3.0
Project Creator : 9and3
public PointCloud CropCloud(PointCloud cloud, List<Curve> curves, bool inverse = false, double scale = 1e10, double tol = 0.001) {
bool[] flags = new bool[cloud.Count];
foreach (Curve crv in curves) {
bool f = crv.TryGetPolyline(out Polyline polyline_); if (!f) continue;
PointCloud cloud_ = new PointCloud(cloud);
Polyline polyline = new Polyline(polyline_);
Plane plane;
Plane.FitPlaneToPoints(polyline, out plane);
Transform xform = Transform.PlaneToPlane(plane, Plane.WorldXY);
polyline.Transform(xform);
cloud_.Transform(xform);
var input = Geometry.RhinClip.PolylineToIntPoint(polyline, scale);
System.Threading.Tasks.Parallel.For(0, cloud.Count, i => {
// for (int i = 0; i < cloud_.Count; i++) {
if (flags[i]) return;
Point3d p = new Point3d(cloud_[i].Location);
var inputP = new IntPoint(p.X * scale, p.Y * scale);
bool flag = Clipper642.Clipper.PointInPolygon(inputP, input) != 0;//;: Clipper642.Clipper.PointInPolygon(inputP, input) == 0;
if (flag)
flags[i] = true;
// }
});
}
int count = 0;
List<int> idList = new List<int>();
//System.Threading.Tasks.Parallel.For(0, cloud.Count, i => {
for (int i = 0; i < cloud.Count; i++) {
bool f = inverse ? !flags[i] : flags[i];
if (f) {
idList.Add(i);
count++;
}
}
//});
int[] idArray = idList.ToArray();
Point3d[] points = new Point3d[count];
Vector3d[] normals = new Vector3d[count];
Color[] colors = new Color[count];
System.Threading.Tasks.Parallel.For(0, idArray.Length, i => {
int id = idArray[i];
var p = cloud[(int)id];
points[i] = p.Location;
normals[i] = p.Normal;
colors[i] = p.Color;
});
PointCloud croppedCloud = new PointCloud();
croppedCloud.AddRange(points, normals, colors);
//PointCloud croppedCloud = new PointCloud();
//for (int i = 0; i < cloud.Count; i++) {
// bool f = inverse ? !flags[i] : flags[i];
// if (f) {
// if (cloud.ContainsNormals) {
// croppedCloud.Add(cloud[i].Location, cloud[i].Normal, cloud[i].Color);
// } else {
// croppedCloud.Add(cloud[i].Location, cloud[i].Color);
// }
// }
//}
return croppedCloud;
}
19
View Source File : CloudSwap.cs
License : GNU Lesser General Public License v3.0
Project Creator : 9and3
License : GNU Lesser General Public License v3.0
Project Creator : 9and3
protected override void SolveInstance(IGH_DataAccess DA) {
GH_Cloud cloud = new GH_Cloud();
DA.GetData(0, ref cloud);
string txt = "CPN";
DA.GetData(1, ref txt);
char[] characters = txt.ToCharArray();
if (characters == null) return;
if (characters.Length != 3) return;
Point3d[] points = new Point3d[cloud.Value.Count];
Vector3d[] normals = new Vector3d[cloud.Value.Count];
System.Drawing.Color[] colors = new System.Drawing.Color[cloud.Value.Count];
//PointCloud swapCloud = new PointCloud();
System.Threading.Tasks.Parallel.For(0, cloud.Value.Count, i => {
//for (int i = 0; i < cloud.Value.Count; i++) {
//swapCloud.AppendNew();
//Points
switch (characters[0]) {
case ('p'):
case ('P'):
points[i] = cloud.Value[i].Location;
break;
case ('c'):
case ('C'):
var color = cloud.Value[i].Color;
points[i] = new Point3d(color.R, color.G, color.B);
break;
case ('n'):
case ('N'):
points[i] = new Point3d(cloud.Value[i].Normal);
break;
}
switch (characters[1]) {
case ('p'):
case ('P'):
normals[i] = new Vector3d(cloud.Value[i].Location);
break;
case ('c'):
case ('C'):
var color = cloud.Value[i].Color;
normals[i] = new Vector3d(color.R, color.G, color.B);
break;
case ('n'):
case ('N'):
normals[i] = new Vector3d(cloud.Value[i].Normal);
break;
}
switch (characters[2]) {
case ('p'):
case ('P'):
colors[i] = cloud.Value[i].Color;
break;
case ('c'):
case ('C'):
colors[i] = cloud.Value[i].Color;
break;
case ('n'):
case ('N'):
colors[i] = cloud.Value[i].Color;
break;
}
// }
});
PointCloud c = new PointCloud();
c.AddRange(points,normals,colors);
DA.SetData(0,new GH_Cloud(c));
}
19
View Source File : IntegrationTests.cs
License : MIT License
Project Creator : Abc-Arbitrage
License : MIT License
Project Creator : Abc-Arbitrage
[Test]
public void should_test_append()
{
Console.WriteLine("Starting test");
var sw = Stopwatch.StartNew();
Parallel.For(0, _nbThreads, threadId =>
{
var logger = LogManager.GetLogger(typeof(IntegrationTests).Name + threadId.ToString());
for (var i = 0; i < _count; i++)
{
var timestamp = Stopwatch.GetTimestamp();
logger.InfoFormat("{0}", timestamp);
_enqueueMicros[threadId][i] = ToMicroseconds(Stopwatch.GetTimestamp() - timestamp);
}
});
LogManager.Shutdown();
var throughput = _count / sw.Elapsed.TotalSeconds;
Console.WriteLine($"Finished test, throughput is: {throughput:N0} msgs/second");
_performanceAppender.PrintTimeTaken();
var streamWriter = new StreamWriter(new FileStream("write-times.csv", FileMode.Create));
foreach (var thread in _enqueueMicros)
{
foreach (var timeTaken in thread)
{
streamWriter.WriteLine(timeTaken);
}
}
Console.WriteLine("Printed total time taken csv");
}
19
View Source File : World.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public void Populate()
{
_rng = new Random(Seed);
People = new Person[Population];
#if !SILVERLIGHT
Parallel.For(0, People.Length, i =>
{
var pos = new Point(NextRandomDouble(), NextRandomDouble());
People[i] = NextRandomDouble() < VictimFraction ? (Person) new Victim(pos) : new Defender(pos);
});
#else
for (int i = 0; i < People.Length; i++)
{
var pos = new Point(NextRandomDouble(), NextRandomDouble());
People[i] = NextRandomDouble() < VictimFraction ? (Person)new Victim(pos) : new Defender(pos);
}
#endif
for (int i = 0; i < People.Length; ++i)
{
People[i].Initialize(this);
}
PropChanged("People");
}
19
View Source File : World.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public void Tick(int cpuCount = 2)
{
if (People != null)
{
int chunkSize = People.Length/cpuCount;
Parallel.For(0, cpuCount, cpu =>
{
int nextChunk = cpu*chunkSize + chunkSize;
for (int i = cpu*chunkSize; i < nextChunk; i++)
{
Person person = People[i];
person.CalculateTarget();
person.UpdatePosition(_deltaT);
}
});
if (OnWorldTick != null)
{
OnWorldTick(this, EventArgs.Empty);
}
}
}
19
View Source File : FifoBillionPointsPageViewModel.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static async Task<List<IRenderableSeriesViewModel>> CreateSeriesAsync(int seriesCount, int pointCount)
{
return await Task.Run(() =>
{
// Create N series of M points async. Return to calling code to set on the chart
IRenderableSeriesViewModel[] series = new IRenderableSeriesViewModel[seriesCount];
// We generate data in parallel as just generating 1,000,000,000 points takes a long time no matter how fast your chart is!
Parallel.For(0, seriesCount, i =>
{
// Temporary buffer for fast filling of DataSeries
var xBuffer = new float[AppendCount];
var yBuffer = new float[AppendCount];
int randomSeed = i * short.MaxValue;
var randomWalkGenerator = new Rand(randomSeed);
var xyDataSeries = new XyDataSeries<float, float>
{
// Required for scrolling / streaming 'first in first out' charts
FifoCapacity = pointCount,
Capacity = pointCount,
// Optional to improve performance when you know in advance whether
// data is sorted ascending and contains float.NaN or not
DataDistributionCalculator = new UserDefinedDistributionCalculator<float, float>
{
ContainsNaN = false,
IsEvenlySpaced = true,
IsSortedAscending = true,
},
// Just replacedociate a random walk generator with the series for more consistent random generation
Tag = randomWalkGenerator
};
int yOffset = i + i;
for (int j = 0; j < pointCount; j += AppendCount)
{
for (int k = 0; k < AppendCount; k++)
{
xBuffer[k] = j + k;
yBuffer[k] = randomWalkGenerator.NextWalk() + yOffset;
}
xyDataSeries.Append(xBuffer, yBuffer);
}
// Store the series
series[i] = new LineRenderableSeriesViewModel
{
DataSeries = xyDataSeries,
Stroke = GetRandomColor()
};
});
// Force a GC Collect before we begin
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
return series.ToList();
});
}
19
View Source File : MainViewModel.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static async Task<List<IRenderableSeriesViewModel>> CreateSeries(int seriesCount, int pointCount)
{
return await Task.Run(() =>
{
// Create N series of M points async. Return to calling code to set on the chart
IRenderableSeriesViewModel[] series = new IRenderableSeriesViewModel[seriesCount];
// We generate data in parallel as just generating 1,000,000,000 points takes a long time no matter how fast your chart is!
Parallel.For(0, seriesCount, i =>
{
// Temporary buffer for fast filling of DataSeries
var xBuffer = new float[AppendCount];
var yBuffer = new float[AppendCount];
int randomSeed = i * short.MaxValue;
var randomWalkGenerator = new Rand(randomSeed);
var xyDataSeries = new XyDataSeries<float, float>()
{
// Required for scrolling / streaming 'first in first out' charts
FifoCapacity = pointCount,
Capacity = pointCount,
// Optional to improve performance when you know in advance whether
// data is sorted ascending and contains float.NaN or not
// see https://www.scichart.com/doreplacedentation/v5.x/webframe.html#Performance_Tips_&_Tricks.html for why
DataDistributionCalculator = new UserDefinedDistributionCalculator<float, float>()
{
ContainsNaN = false,
IsEvenlySpaced = true,
IsSortedAscending = true,
},
// Just replacedociate a random walk generator with the series for more consistent random generation
Tag = randomWalkGenerator,
};
int yOffset = i + i;
for (int j = 0; j < pointCount; j += AppendCount)
{
for (int k = 0; k < AppendCount; k++)
{
xBuffer[k] = j + k;
yBuffer[k] = randomWalkGenerator.NextWalk() + yOffset;
}
// Append blocks of 10k points for performance
// see https://www.scichart.com/doreplacedentation/v5.x/webframe.html#Performance_Tips_&_Tricks.html for why
xyDataSeries.Append(xBuffer, yBuffer);
}
// Store the series
series[i] = new LineRenderableSeriesViewModel()
{
DataSeries = xyDataSeries,
Stroke = Colors.RandomColor()
};
});
// Force a GC Collect before we begin
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true);
return series.ToList();
});
}
19
View Source File : Program.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
private static async Task Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var services = new ServiceCollection();
services.AddLogging(builder =>
{
builder.AddConfiguration(configuration.GetSection("Logging"));
// register our customized file logger instead of the "standard" one
builder.AddFile<CustomFileLoggerProvider>(configure: o => o.RootPath = AppContext.BaseDirectory);
});
await using (ServiceProvider sp = services.BuildServiceProvider())
{
// create logger factory
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
// generate a larger amount of messages
Parallel.For(0, 1000, i =>
{
var logger = loggerFactory.CreateLogger("Thread" + Thread.CurrentThread.ManagedThreadId);
var logLevel = (LogLevel)(i % (int)(LogLevel.Critical + 1));
logger.Log(logLevel, 0, "Msg" + i, null, (s, _) => s);
});
}
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,] SetValues(float[,] array, float value, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
array[i, j] = value;
});
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static bool[,] SetValues(bool[,] array, bool value, Area dmns = null)
{
if (dmns == null)
dmns = new Area(AreaManager.ActiveArea.x0, AreaManager.ActiveArea.x1 * 2, AreaManager.ActiveArea.z0, AreaManager.ActiveArea.z1 * 2);
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
array[i, j] = value;
});
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,,] SetRange(float[,,] array, float[,] range, int channel, float rangeLow, float rangeHigh, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
int channelCount = array.GetLength(2);
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
if (range[i, j] >= rangeLow && range[i, j] <= rangeHigh)
{
for (int k = 0; k < channelCount; k++)
array[i, j, k] = 0;
array[i, j, channel] = 1;
}
}
});
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,,] SetRangeBlend(float[,,] array, float[,] range, int channel, float rangeLow, float rangeHigh, float rangeBlendLow, float rangeBlendHigh, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
int channelLength = array.GetLength(2);
for (int i = dmns.x0; i < dmns.x1; i++)
{
Parallel.For(dmns.z0, dmns.z1, j =>
{
float[] normalised = new float[channelLength];
if (range[i, j] >= rangeLow && range[i, j] <= rangeHigh)
{
for (int k = 0; k < channelLength; k++)
array[i, j, k] = 0;
array[i, j, channel] = 1;
}
else if (range[i, j] >= rangeBlendLow && range[i, j] < rangeLow)
{
float normalisedRange = range[i, j] - rangeBlendLow;
float newRange = rangeLow - rangeBlendLow;
float rangeBlend = normalisedRange / newRange; // Holds data about the texture weight between the blend ranges.
for (int k = 0; k < channelLength; k++) // Gets the weights of the textures in the pos.
{
if (k == channel)
array[i, j, channel] = rangeBlend;
else
array[i, j, k] = array[i, j, k] * Mathf.Clamp01(1f - rangeBlend);
normalised[k] = array[i, j, k];
}
float normalisedWeights = normalised.Sum();
for (int k = 0; k < channelLength; k++)
{
normalised[k] /= normalisedWeights;
array[i, j, k] = normalised[k];
}
}
else if (range[i, j] > rangeHigh && range[i, j] <= rangeBlendHigh)
{
float normalisedRange = range[i, j] - rangeHigh;
float newRange = rangeBlendHigh - rangeHigh;
float rangeBlend = normalisedRange / newRange; // Holds data about the texture weight between the blend ranges.
float rangeBlendInverted = 1 - rangeBlend;
for (int k = 0; k < channelLength; k++) // Gets the weights of the textures in the pos.
{
if (k == channel)
array[i, j, channel] = rangeBlendInverted;
else
array[i, j, k] = array[i, j, k] * Mathf.Clamp01(1f - rangeBlendInverted);
normalised[k] = array[i, j, k];
}
float normalisedWeights = normalised.Sum();
for (int k = 0; k < channelLength; k++)
{
normalised[k] /= normalisedWeights;
array[i, j, k] = normalised[k];
}
}
});
}
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,] ClampValues(float[,] array, float minValue, float maxValue, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
array[i, j] = Mathf.Clamp(array[i, j], minValue, maxValue);
});
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,] Rotate(float[,] array, bool CW, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
float[,] newArray = new float[array.GetLength(0), array.GetLength(1)];
if (CW)
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
newArray[i, j] = array[j, dmns.x1 - i - 1];
});
}
else
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
newArray[i, j] = array[dmns.z1 - j - 1, i];
});
}
return newArray;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,,] Rotate(float[,,] array, bool CW, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
int channelLength = array.GetLength(2);
float[,,] newArray = new float[array.GetLength(0), array.GetLength(1), array.GetLength(2)];
if (CW)
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
for (int k = 0; k < channelLength; k++)
newArray[i, j, k] = array[j, dmns.x1 - i - 1, k];
}
});
}
else
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
for (int k = 0; k < channelLength; k++)
newArray[i, j, k] = array[dmns.z1 - j - 1, i, k];
}
});
}
return newArray;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,] ShortMapToFloatArray(TerrainMap<short> terrainMap)
{
float[,] array = new float[terrainMap.res, terrainMap.res];
int arrayLength = array.GetLength(0);
Parallel.For(0, arrayLength, i =>
{
for (int j = 0; j < arrayLength; j++)
array[i, j] = BitUtility.Short2Float(terrainMap[i, j]);
});
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static byte[] FloatArrayToByteArray(float[,] array)
{
short[] shortArray = new short[array.GetLength(0) * array.GetLength(1)];
int arrayLength = array.GetLength(0);
Parallel.For(0, arrayLength, i =>
{
for (int j = 0; j < arrayLength; j++)
shortArray[(i * arrayLength) + j] = BitUtility.Float2Short(array[i, j]);
});
byte[] byteArray = new byte[shortArray.Length * 2];
Buffer.BlockCopy(shortArray, 0, byteArray, 0, byteArray.Length);
return byteArray;
}
19
View Source File : PrefabHierarchyTreeView.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static PrefabDataHolder[] PrefabDataFromSelection(PrefabHierarchyTreeView treeView)
{
var selection = treeView.GetSelection();
var treeList = treeView.treeModel.m_Data.ToList();
PrefabDataHolder[] prefabDataList = new PrefabDataHolder[selection.Count];
Parallel.For(0, selection.Count, i =>
{
prefabDataList[i] = treeList.Find(x => x.id == selection.ElementAt(i)).prefabDataHolder;
});
return prefabDataList;
}
19
View Source File : TerrainManager.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
private static IEnumerator SetSplatMaps(MapInfo mapInfo, int progressID)
{
SplatMapRes = mapInfo.splatRes;
SetSplatMap(mapInfo.splatMap, LayerType.Ground);
SetSplatMap(mapInfo.biomeMap, LayerType.Biome);
SetAlphaMap(mapInfo.alphaMap);
yield return null;
Progress.Report(progressID, .8f, "Loaded: Splats.");
TopologyData.Set(mapInfo.topology);
Parallel.For(0, TerrainTopology.COUNT, i =>
{
if (CurrentLayerType != LayerType.Topology || TopologyLayer != i)
SetSplatMap(TopologyData.GetTopologyLayer(TerrainTopology.IndexToType(i)), LayerType.Topology, i);
});
SetSplatMap(TopologyData.GetTopologyLayer(TerrainTopology.IndexToType(TopologyLayer)), LayerType.Topology, TopologyLayer);
Progress.Report(progressID, .9f, "Loaded: Topologies.");
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,,] SetValues(float[,,] array, int channel, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
int channelLength = array.GetLength(2);
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
for (int k = 0; k < channelLength; k++)
array[i, j, k] = 0;
array[i, j, channel] = 1;
}
});
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static bool[,] SetRange(bool[,] array, float[,] range, bool value, float rangeLow, float rangeHigh, Area dmns = null)
{
if (dmns == null)
dmns = new Area(AreaManager.ActiveArea.x0, AreaManager.ActiveArea.x1 * 2, AreaManager.ActiveArea.z0, AreaManager.ActiveArea.z1 * 2);
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
if (range[i * 2, j * 2] > rangeLow && range[i * 2, j * 2] < rangeHigh)
array[i, j] = value;
}
});
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,,] SetRiver(float[,,] array, float[,] landHeights, float[,] waterHeights, bool aboveTerrain, int channel, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
int channelLength = array.GetLength(2);
if (aboveTerrain)
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
if (waterHeights[i, j] > 500 && waterHeights[i, j] > landHeights[i, j])
{
for (int k = 0; k < channelLength; k++)
array[i, j, k] = 0;
array[i, j, channel] = 1;
}
}
});
}
else
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
if (waterHeights[i, j] > 500)
{
for (int k = 0; k < channelLength; k++)
array[i, j, k] = 0;
array[i, j, channel] = 1;
}
}
});
}
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static bool[,] SetRiver(bool[,] array, float[,] landHeights, float[,] waterHeights, bool aboveTerrain, bool value, Area dmns = null)
{
if (dmns == null)
dmns = new Area(AreaManager.ActiveArea.x0, AreaManager.ActiveArea.x1 * 2, AreaManager.ActiveArea.z0, AreaManager.ActiveArea.z1 * 2);
if (aboveTerrain)
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
if (waterHeights[i, j] > 500 && waterHeights[i, j] > landHeights[i, j])
array[i, j] = value;
}
});
}
else
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
if (waterHeights[i, j] > 500)
array[i, j] = value;
}
});
}
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static bool[,] Rotate(bool[,] array, bool CW, Area dmns = null)
{
if (dmns == null)
dmns = new Area(AreaManager.ActiveArea.x0, AreaManager.ActiveArea.x1 * 2, AreaManager.ActiveArea.z0, AreaManager.ActiveArea.z1 * 2);
bool[,] newArray = new bool[array.GetLength(0), array.GetLength(1)];
if (CW)
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
newArray[i, j] = array[j, dmns.x1 - i - 1];
});
}
else
{
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
newArray[i, j] = array[dmns.z1 - j - 1, i];
});
}
return newArray;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,] Invert(float[,] array, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
array[i, j] = 1 - array[i, j];
});
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,,] Invert(float[,,] array, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
int channelLength = array.GetLength(2);
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
for (int k = 0; k < channelLength; k++)
array[i, j, k] = 1 - array[i, j, k];
}
});
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static bool[,] Invert(bool[,] array, Area dmns = null)
{
if (dmns == null)
dmns = new Area(AreaManager.ActiveArea.x0, AreaManager.ActiveArea.x1 * 2, AreaManager.ActiveArea.z0, AreaManager.ActiveArea.z1 * 2);
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
array[i, j] = !array[i, j];
});
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,] Normalise(float[,] array, float normaliseLow, float normaliseHigh, Area dmns = null)
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
float highestPoint = 0f, lowestPoint = 1f, heightRange = 0f, normalisedHeightRange = 0f;
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
if (array[i, j] < lowestPoint)
lowestPoint = array[i, j];
else if (array[i, j] > highestPoint)
highestPoint = array[i, j];
}
});
heightRange = highestPoint - lowestPoint;
normalisedHeightRange = normaliseHigh - normaliseLow;
Parallel.For(dmns.x0, dmns.x1, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
array[i, j] = normaliseLow + ((array[i, j] - lowestPoint) / heightRange) * normalisedHeightRange;
});
return array;
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,] Offset(float[,] array, float offset, bool clampOffset, Area dmns = null)
{
float[,] tempArray = array;
CancellationTokenSource source = new CancellationTokenSource();
ParallelOptions options = new ParallelOptions() { CancellationToken = source.Token};
try
{
if (dmns == null)
dmns = AreaManager.ActiveArea;
Parallel.For(dmns.x0, dmns.x1, options, i =>
{
for (int j = dmns.z0; j < dmns.z1; j++)
{
if (clampOffset == true)
{
if ((array[i, j] + offset > 1f || array[i, j] + offset < 0f))
source.Cancel();
else
tempArray[i, j] += offset;
}
else
tempArray[i, j] += offset;
}
});
}
catch (OperationCanceledException)
{
return array;
}
return tempArray;
}
19
View Source File : WorldConverter.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static MapInfo ConvertMaps(MapInfo terrains, TerrainMap<byte> splatMap, TerrainMap<byte> biomeMap, TerrainMap<byte> alphaMap)
{
terrains.splatMap = new float[splatMap.res, splatMap.res, 8];
terrains.biomeMap = new float[biomeMap.res, biomeMap.res, 4];
terrains.alphaMap = new bool[alphaMap.res, alphaMap.res];
var groundTask = Task.Run(() =>
{
Parallel.For(0, terrains.splatRes, i =>
{
for (int j = 0; j < terrains.splatRes; j++)
for (int k = 0; k < 8; k++)
terrains.splatMap[i, j, k] = BitUtility.Byte2Float(splatMap[k, i, j]);
});
});
var biomeTask = Task.Run(() =>
{
Parallel.For(0, terrains.splatRes, i =>
{
for (int j = 0; j < terrains.splatRes; j++)
for (int k = 0; k < 4; k++)
terrains.biomeMap[i, j, k] = BitUtility.Byte2Float(biomeMap[k, i, j]);
});
});
var alphaTask = Task.Run(() =>
{
Parallel.For(0, terrains.splatRes, i =>
{
for (int j = 0; j < terrains.splatRes; j++)
{
if (alphaMap[0, i, j] > 0)
terrains.alphaMap[i, j] = true;
else
terrains.alphaMap[i, j] = false;
}
});
});
Task.WaitAll(groundTask, biomeTask, alphaTask);
return terrains;
}
19
View Source File : WorldConverter.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static WorldSerialization TerrainToWorld(Terrain land, Terrain water, (int prefab, int path, int terrain) ID)
{
WorldSerialization world = new WorldSerialization();
world.world.size = (uint) land.terrainData.size.x;
var textureResolution = SplatMapRes;
byte[] splatBytes = new byte[textureResolution * textureResolution * 8];
var splatMap = new TerrainMap<byte>(splatBytes, 8);
var splatTask = Task.Run(() =>
{
Parallel.For(0, 8, i =>
{
for (int j = 0; j < textureResolution; j++)
for (int k = 0; k < textureResolution; k++)
splatMap[i, j, k] = BitUtility.Float2Byte(Ground[j, k, i]);
});
splatBytes = splatMap.ToByteArray();
});
byte[] biomeBytes = new byte[textureResolution * textureResolution * 4];
var biomeMap = new TerrainMap<byte>(biomeBytes, 4);
var biomeTask = Task.Run(() =>
{
Parallel.For(0, 4, i =>
{
for (int j = 0; j < textureResolution; j++)
for (int k = 0; k < textureResolution; k++)
biomeMap[i, j, k] = BitUtility.Float2Byte(Biome[j, k, i]);
});
biomeBytes = biomeMap.ToByteArray();
});
byte[] alphaBytes = new byte[textureResolution * textureResolution * 1];
var alphaMap = new TerrainMap<byte>(alphaBytes, 1);
bool[,] terrainHoles = GetAlphaMap();
var alphaTask = Task.Run(() =>
{
Parallel.For(0, textureResolution, i =>
{
for (int j = 0; j < textureResolution; j++)
alphaMap[0, i, j] = BitUtility.Bool2Byte(terrainHoles[i, j]);
});
alphaBytes = alphaMap.ToByteArray();
});
var topologyTask = Task.Run(() => TopologyData.SaveTopologyLayers());
foreach (PrefabDataHolder p in PrefabManager.CurrentMapPrefabs)
{
if (p.prefabData != null)
{
p.UpdatePrefabData(); // Updates the prefabdata before saving.
world.world.prefabs.Insert(0, p.prefabData);
}
}
Progress.Report(ID.prefab, 0.99f, "Saved " + PrefabManager.CurrentMapPrefabs.Length + " prefabs.");
foreach (PathDataHolder p in PathManager.CurrentMapPaths)
{
if (p.pathData != null)
{
p.pathData.nodes = new VectorData[p.transform.childCount];
for (int i = 0; i < p.transform.childCount; i++)
{
Transform g = p.transform.GetChild(i);
p.pathData.nodes[i] = g.position - MapOffset;
}
world.world.paths.Insert(0, p.pathData);
}
}
Progress.Report(ID.path, 0.99f, "Saved " + PathManager.CurrentMapPaths.Length + " paths.");
byte[] landHeightBytes = FloatArrayToByteArray(land.terrainData.GetHeights(0, 0, HeightMapRes, HeightMapRes));
byte[] waterHeightBytes = FloatArrayToByteArray(water.terrainData.GetHeights(0, 0, HeightMapRes, HeightMapRes));
Task.WaitAll(splatTask, biomeTask, alphaTask, topologyTask);
Progress.Report(ID.terrain, 0.99f, "Saved " + TerrainSize.x + " size map.");
world.AddMap("terrain", landHeightBytes);
world.AddMap("height", landHeightBytes);
world.AddMap("water", waterHeightBytes);
world.AddMap("splat", splatBytes);
world.AddMap("biome", biomeBytes);
world.AddMap("alpha", alphaBytes);
world.AddMap("topology", TopologyData.GetTerrainMap().ToByteArray());
return world;
}
19
View Source File : TopologyData.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static float[,,] GetTopologyLayer(int layer)
{
TerrainMap<int> topology = GetTerrainMap();
float[,,] splatMap = new float[topology.res, topology.res, 2];
Parallel.For(0, topology.res, i =>
{
for (int j = 0; j < topology.res; j++)
{
if ((topology[i, j] & layer) != 0)
splatMap[i, j, 0] = 1f;
else
splatMap[i, j, 1] = 1f;
}
});
return splatMap;
}
19
View Source File : TopologyData.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static void SaveTopologyLayers()
{
TerrainMap<int> topologyMap = GetTerrainMap();
Parallel.For(0, TerrainTopology.COUNT, i =>
{
Parallel.For(0, topologyMap.res, j =>
{
for (int k = 0; k < topologyMap.res; k++)
{
if (Topology[i][j, k, 0] > 0)
topologyMap[j, k] = topologyMap[j, k] | TerrainTopology.IndexToType(i);
if (Topology[i][j, k, 1] > 0)
topologyMap[j, k] = topologyMap[j, k] & ~TerrainTopology.IndexToType(i);
}
});
});
Data = topologyMap.ToByteArray();
}
19
View Source File : ExcelWriteWrapper.cs
License : MIT License
Project Creator : AdvanceOpen
License : MIT License
Project Creator : AdvanceOpen
public static string GenericWrite()
{
string filePath;
using (var context = ContextFactory.GetWriteContext("用户数据"))
{
Parallel.For(0, 4, index =>
{
var sheetName = $"Sheet{index}";
var sheet = context.CrateSheet<UserExportDto>(sheetName);
for (int i = 0; i < 102000; i++)
{
sheet.AppendData(sheetName, new UserExportDto { Account = $"{index}-{i}-2010211", Name = $"{index}-{i}-用户用户", IsConfirm = i % 2 == 0, IsMan = i % 2 == 0 });
}
});
filePath = context.Save();
Console.WriteLine($"文件路径:{filePath}");
}
return filePath;
}
19
View Source File : PollProxy.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private void Run()
{
var configs = ZeroApplication.Config.GetConfigs(p => p.StationType != ZeroStationType.Dispatcher);
ZSocket[] sockets = new ZSocket[configs.Length * 2];
int idx = 0;
foreach (var config in configs)
{
sockets[idx++] = ZSocket.CreateServiceSocket($"inproc://{config.StationName}_Proxy", ZSocketType.ROUTER);
sockets[idx++] = ZSocket.CreateClientSocket(config.RequestAddress, ZSocketType.DEALER);
}
WaitCount = 0;
ZeroTrace.SystemLog("ConnectionProxy", "Listen");
using (var pool = ZmqPool.CreateZmqPool())
{
pool.Prepare(sockets, ZPollEvent.In);
_waitToken.Release();
//SystemManager.Instance.HeartReady(StationName, RealName);
while (!RunTaskCancel.Token.IsCancellationRequested)
{
if (!pool.Poll())
continue;
Parallel.For(0, configs.Length, index =>
{
CheckCall(pool, index * 2);
CheckResult(pool, index * 2 + 1);
});
}
}
_waitToken.Release();
}
19
View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : AliFlux
License : MIT License
Project Creator : AliFlux
async void showMbTiles(string path, string stylePath, int minX, int minY, int maxX, int maxY, int zoom, double size = 512, double scale = 1)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
// load style and font
var style = new VectorTileRenderer.Style(stylePath);
style.FontDirectory = mainDir + @"styles/fonts/";
// set pbf as tile provider
var provider = new VectorTileRenderer.Sources.MbTilesSource(path);
style.SetSourceProvider(0, provider);
BitmapSource[,] bitmapSources = new BitmapSource[maxX - minX + 1, maxY - minY + 1];
// loop through tiles and render them
Parallel.For(minX, maxX + 1, (int x) =>
{
Parallel.For(minY, maxY + 1, async (int y) =>
{
var canvas = new SkiaCanvas();
var bitmapR = await Renderer.Render(style, canvas, x, y, zoom, size, size, scale);
if (bitmapR == null)
{
}
bitmapSources[x - minX, maxY - y] = bitmapR;
});
});
// merge the tiles and show it
var bitmap = mergeBitmaps(bitmapSources);
demoImage.Source = bitmap;
scrollViewer.Background = new SolidColorBrush(style.GetBackgroundColor(zoom));
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine(elapsedMs + "ms time");
}
19
View Source File : Transformer.cs
License : MIT License
Project Creator : allisterb
License : MIT License
Project Creator : allisterb
protected virtual StageResult Transform(int? recordBatchSize = null, int? recordLimit = null, Dictionary<string, string> options = null)
{
if (!ParallelExecution || InputRecords.Count < 100 || ((RecordLimitSize > 0) && (RecordLimitSize < 100)))
{
using (Operation transformOp = Begin("Transforming {0} records using sequential execution", InputRecords.Count))
{
for (int i = 0; i < InputRecords.Count; i++)
{
OutputRecords.Add(TransformInputToOutput(this, WriterOptions, InputRecords[i]));
if ((i + 1) % 1000 == 0)
{
Info("Transformed range {0} to {1} of {2} records...", (i + 1) - 1000, i + 1, InputRecords.Count);
}
if ((RecordLimitSize > 0) && (i + 1 == RecordLimitSize))
{
Info("Stopping transformation at record limit {0}.", i + 1);
transformOp.Complete();
break;
}
}
transformOp.Complete();
}
}
else
{
int limit = RecordLimitSize > 0 ? RecordLimitSize <= InputRecords.Count ? RecordLimitSize : InputRecords.Count : InputRecords.Count;
using (Operation transformOp = Begin("Transforming {0} records using parallel execution", limit))
{
ConcurrentDictionary<int, TRecord> concurrentOutputDictionary = new ConcurrentDictionary<int, TRecord>();
Parallel.For(0, limit, (i, loop) =>
{
TRecord output = TransformInputToOutput(this, WriterOptions, InputRecords[i]);
concurrentOutputDictionary.TryAdd(i, output);
if ((i + 1) % 1000 == 0)
{
Info("Transformed range {0} to {1} of {2} records...", (i + 1) - 1000, i + 1, InputRecords.Count);
}
});
OutputRecords = concurrentOutputDictionary.Values.ToList();
transformOp.Complete();
}
}
Info("Transformed {0} records with maximum {1} features to {2}.", OutputRecords.Count, OutputRecords.Max(r => r.Features.Count), OutputFileName);
return StageResult.SUCCESS;
}
19
View Source File : AllureLifeCycleTest.cs
License : Apache License 2.0
Project Creator : allure-framework
License : Apache License 2.0
Project Creator : allure-framework
[Test, Description("Integration Test")]
public void IntegrationTest()
{
Parallel.For(0, 2, i =>
{
AllureLifecycle cycle = AllureLifecycle.Instance;
var container = DataGenerator.GetTestResultContainer();
var beforeFeature = DataGenerator.GetFixture(Fixture.BeforeFeature);
var afterFeature = DataGenerator.GetFixture(Fixture.AfterFeature);
var beforeScenario = DataGenerator.GetFixture(Fixture.BeforeScenario);
var afterScenario = DataGenerator.GetFixture(Fixture.AfterScenario);
var test = DataGenerator.GetTestResult();
var fixtureStep = DataGenerator.GetStep();
var step1 = DataGenerator.GetStep();
var step2 = DataGenerator.GetStep();
var step3 = DataGenerator.GetStep();
var txtAttach = DataGenerator.GetAttachment(".txt");
var txtAttachWithNoExt = DataGenerator.GetAttachment();
cycle
.StartTestContainer(container)
.StartBeforeFixture(container.uuid, beforeFeature.uuid, beforeFeature.fixture)
.StartStep(fixtureStep.uuid, fixtureStep.step)
.StopStep(x => x.status = Status.preplaceded)
.AddAttachment("text file", "text/xml", txtAttach.path)
.AddAttachment(txtAttach.path)
.UpdateFixture(beforeFeature.uuid, f => f.status = Status.preplaceded)
.StopFixture(beforeFeature.uuid)
.StartBeforeFixture(container.uuid, beforeScenario.uuid, beforeScenario.fixture)
.UpdateFixture(beforeScenario.uuid, f => f.status = Status.preplaceded)
.StopFixture(beforeScenario.uuid)
.StartTestCase(container.uuid, test)
.StartStep(step1.uuid, step1.step)
.StopStep(x => x.status = Status.preplaceded)
.StartStep(step2.uuid, step2.step)
.AddAttachment("unknown file", "text/xml", txtAttachWithNoExt.content)
.StopStep(x => x.status = Status.broken)
.StartStep(step3.uuid, step3.step)
.StopStep(x => x.status = Status.skipped)
.AddScreenDiff(test.uuid, "expected.png", "actual.png", "diff.png")
.StopTestCase(x =>
{
x.status = Status.broken;
x.statusDetails = new StatusDetails()
{
flaky = true,
known = true,
message = "Oh my!",
trace = "That was really bad...",
muted = true
};
})
.StartAfterFixture(container.uuid, afterScenario.uuid, afterScenario.fixture)
.UpdateFixture(afterScenario.uuid, f => f.status = Status.preplaceded)
.StopFixture(afterScenario.uuid)
.StartAfterFixture(container.uuid, afterFeature.uuid, afterFeature.fixture)
.StopFixture(f => f.status = Status.preplaceded)
.WriteTestCase(test.uuid)
.StopTestContainer(container.uuid)
.WriteTestContainer(container.uuid);
});
}
19
View Source File : IdGeneraterTests.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
[Fact]
public void TestSpeed()
{
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
Parallel.For(1, 1000000, index =>
{
IdGenerater.GetNextId();
});
stopwatch.Stop();
//持续时间: 517 毫秒
_output.WriteLine(stopwatch.ElapsedMilliseconds.ToString());
stopwatch.Reset();
}
19
View Source File : Program.cs
License : MIT License
Project Creator : altimesh
License : MIT License
Project Creator : altimesh
public static void Reference(NaiveMatrix result, NaiveMatrix A, NaiveMatrix B)
{
Parallel.For(0, A.Height, (i) =>
{
for (int j = 0; j < B.Width; ++j)
{
float acreplaced = 0.0F;
for (int k = 0; k < A.Width; ++k)
{
acreplaced += A[A.Width * i + k] * B[B.Width * k + j];
}
result[B.Width * i + j] = acreplaced;
}
});
}
19
View Source File : Program.cs
License : MIT License
Project Creator : altimesh
License : MIT License
Project Creator : altimesh
static void Main(string[] args)
{
if (args.Length == 0)
{
args = new string[] { "512", "512", "512", "512" };
}
const int redo = 10;
int heightA = Convert.ToInt32(args[0]);
int widthA = Convert.ToInt32(args[1]);
int heightB = Convert.ToInt32(args[2]);
int widthB = Convert.ToInt32(args[3]);
if (widthA != heightB)
{
throw new ArgumentException("invalid data -- incompatible matrices");
}
Console.WriteLine("Execution Naive matrix mul with sizes ({0}, {1}) x ({2}, {3})", heightA, widthA, heightB, widthB);
NaiveMatrix matrixA = new NaiveMatrix(widthA, heightA);
NaiveMatrix matrixB = new NaiveMatrix(widthB, heightB);
NaiveMatrix res_net = new NaiveMatrix(widthB, heightA);
NaiveMatrix res_cuda = new NaiveMatrix(widthB, heightA);
double numberCompute = ((double)matrixA.Height * (double)matrixA.Width * (double)matrixB.Width) * 3.0E-9;
matrixA.FillMatrix();
matrixB.FillMatrix();
Random rand = new Random();
#region CUDA
HybRunner runner = HybRunner.Cuda("NaiveMatrix_CUDA.dll").SetDistrib(4, 5, 8, 32, 32, 0);
dynamic wrapper = runner.Wrap(new Program());
for (int i = 0; i < redo; ++i)
{
wrapper.ComputeRowsOfProduct(res_cuda, matrixA, matrixB, 0, res_cuda.Height);
}
#endregion
#region C#
for (int i = 0; i < redo; ++i)
{
Parallel.For(0, res_net.Height, (line) =>
{
ComputeRowsOfProduct(res_net, matrixA, matrixB, line, line + 1);
});
}
#endregion
Console.Out.WriteLine("DONE");
}
19
View Source File : Program.cs
License : MIT License
Project Creator : altimesh
License : MIT License
Project Creator : altimesh
static void Main(string[] args)
{
if (args.Length == 0)
{
args = new string[] { "512", "512", "512", "512" };
}
const int redo = 10;
int heightA = Convert.ToInt32(args[0]);
int widthA = Convert.ToInt32(args[1]);
int heightB = Convert.ToInt32(args[2]);
int widthB = Convert.ToInt32(args[3]);
if (widthA != heightB)
{
throw new ArgumentException("invalid data -- incompatible matrices");
}
Console.WriteLine("Execution Naive matrix mul with sizes ({0}, {1}) x ({2}, {3})", heightA, widthA, heightB, widthB);
NaiveMatrix matrixA = new NaiveMatrix(widthA, heightA);
NaiveMatrix matrixB = new NaiveMatrix(widthB, heightB);
NaiveMatrix res_net = new NaiveMatrix(widthB, heightA);
NaiveMatrix res_cuda = new NaiveMatrix(widthB, heightA);
double numberCompute = ((double)matrixA.Height * (double)matrixA.Width * (double)matrixB.Width) * 3.0E-9;
matrixA.FillMatrix();
matrixB.FillMatrix();
Random rand = new Random();
#region CUDA
HybRunner runner = HybRunner.Cuda().SetDistrib(4, 5, 8, 32, 32, 0);
dynamic wrapper = runner.Wrap(new Program());
for (int i = 0; i < redo; ++i)
{
wrapper.ComputeRowsOfProduct(res_cuda, matrixA, matrixB, 0, res_cuda.Height);
}
#endregion
#region C#
for (int i = 0; i < redo; ++i)
{
Parallel.For(0, res_net.Height, (line) =>
{
ComputeRowsOfProduct(res_net, matrixA, matrixB, line, line + 1);
});
}
#endregion
Console.Out.WriteLine("DONE");
}
19
View Source File : 01-stack-gpu-solution.cs
License : MIT License
Project Creator : altimesh
License : MIT License
Project Creator : altimesh
[EntryPoint]
public static void ParForGPU(ushort[] output, ushort[] input, int width, int height)
{
Parallel.For(window, height - window, j =>
{
// var buffer = new ushort[windowCount * windowCount];
var buffer = new StackArray<ushort>(windowCount * windowCount);
for (int i = window; i < width - window; ++i)
{
for (int k = -window; k <= window; ++k)
{
for (int p = -window; p <= window; ++p)
{
int bufferIndex = (k + window) * windowCount + p + window;
int pixelIndex = (j + k) * width + (i + p);
buffer[bufferIndex] = input[pixelIndex];
}
}
Bitonic.Sort(buffer.data, 0, windowCount * windowCount);
output[j * width + i] = buffer[(windowCount * windowCount) / 2];
}
}) ;
}
19
View Source File : 02-dice-gpu.cs
License : MIT License
Project Creator : altimesh
License : MIT License
Project Creator : altimesh
[EntryPoint]
public static void ParForGPU(ushort[] output, ushort[] input, int width, int height)
{
// change for a Parallel2D.For
Parallel.For(window, height - window, j =>
{
var buffer = new StackArray<ushort>(windowCount * windowCount);
for (int i = window; i < width - window; ++i)
{
for (int k = -window; k <= window; ++k)
{
for (int p = -window; p <= window; ++p)
{
int bufferIndex = (k + window) * windowCount + p + window;
int pixelIndex = (j + k) * width + (i + p);
buffer[bufferIndex] = input[pixelIndex];
}
}
Bitonic.Sort(buffer.data, 0, windowCount * windowCount);
output[j * width + i] = buffer[(windowCount * windowCount) / 2];
}
}) ;
}
19
View Source File : Form1.cs
License : MIT License
Project Creator : altimesh
License : MIT License
Project Creator : altimesh
private void render()
{
int[] iterCount = new int[W * H];
Stopwatch watch = new Stopwatch();
long elapsedMilliseconds;
watch.Start();
switch (flavor)
{
case Flavors.AVX:
MandelbrotAVX.Render(iterCount, fromX, fromY, sX, sY, 1.0F / W, 1.0F / H, H, W, 0, H, maxiter);
break;
case Flavors.AVX2:
MandelbrotAVX2.Render(iterCount, fromX, fromY, sX, sY, 1.0F / W, 1.0F / H, H, W, 0, H, maxiter);
break;
case Flavors.AVX512:
MandelbrotAVX512.Render(iterCount, fromX, fromY, sX, sY, 1.0F / W, 1.0F / H, H, W, 0, H, maxiter);
break;
case Flavors.CUDA:
MandelbrotCUDA.Render2D(iterCount, fromX, fromY, sX, sY, 1.0F / W, 1.0F / H, H, W, maxiter);
cuda.DeviceSynchronize();
break;
case Flavors.Source:
default:
int slice = H / Environment.ProcessorCount;
Parallel.For(0, Environment.ProcessorCount, tid =>
{
int lineFrom = tid * slice;
int lineTo = Math.Min(H, lineFrom + slice);
Mandelbrots.Mandelbrot.Render(iterCount, fromX, fromY, sX, sY, 1.0F / W, 1.0F / H, H, W, lineFrom, lineTo, maxiter);
});
break;
}
watch.Stop();
for (int j = 0; j < H; ++j)
{
for (int i = 0; i < W; ++i)
{
int color = GetMandelbrotColor(iterCount[j * W + i], maxiter);
image.SetPixel(i, j, Color.FromArgb(color));
}
}
elapsedMilliseconds = watch.ElapsedMilliseconds;
if(flavor == Flavors.CUDA)
{
elapsedMilliseconds = runnerCUDA.LastKernelDuration.ElapsedMilliseconds;
}
label2.Text = "Rendering Time : " + watch.ElapsedMilliseconds + " ms";
Rendering.Refresh();
}
19
View Source File : ColorSpectrum.cs
License : MIT License
Project Creator : amwx
License : MIT License
Project Creator : amwx
private void DrawValueSaturationBitmap()
{
using (var lok = (_tempBitmap as WriteableBitmap).Lock())
{
unsafe
{
var pixels = (uint*)(void*)lok.Address;
var count = _defBitmapSize * _defBitmapSize;
var hue = Hue;
float size = _defBitmapSize;
Parallel.For(0, _defBitmapSize, i =>
{
int start = i * _defBitmapSize;
uint x = 0;
var sat = (1 - (i / (size - 1)));
for (int j = start; j < start + _defBitmapSize; j++)
{
var value = (x / (size - 1));
Color2.HSVToUInt(hue, sat, value, out uint num);
pixels[j] = num;
x++;
}
});
}
}
}
19
View Source File : ColorSpectrum.cs
License : MIT License
Project Creator : amwx
License : MIT License
Project Creator : amwx
private void DrawValueHueBitmap()
{
using (var lok = (_tempBitmap as WriteableBitmap).Lock())
{
unsafe
{
var pixels = (uint*)(void*)lok.Address;
var count = _defBitmapSize * _defBitmapSize;
var sat = Color.Saturationf;
float size = _defBitmapSize;
Parallel.For(0, _defBitmapSize, i =>
{
int start = i * _defBitmapSize;
uint x = 0;
var hue = 360 - ((i / size) * 360);
//var sat = (1 - (i / (size - 1)));
for (int j = start; j < start + _defBitmapSize; j++)
{
var value = x / size;
Color2.HSVToUInt(hue, sat, value, out uint num);
pixels[j] = num;
x++;
}
});
}
}
}
19
View Source File : ColorSpectrum.cs
License : MIT License
Project Creator : amwx
License : MIT License
Project Creator : amwx
private void DrawSaturationHueBitmap()
{
using (var lok = (_tempBitmap as WriteableBitmap).Lock())
{
unsafe
{
var pixels = (uint*)(void*)lok.Address;
var count = _defBitmapSize * _defBitmapSize;
var value = Color.Valuef;
float size = _defBitmapSize;
Parallel.For(0, _defBitmapSize, i =>
{
int start = i * _defBitmapSize;
uint x = 0;
var hue = 360 - ((i / size) * 360);
//var sat = (1 - (i / (size - 1)));
for (int j = start; j < start + _defBitmapSize; j++)
{
var sat = x / size;
Color2.HSVToUInt(hue, sat, value, out uint num);
pixels[j] = num;
x++;
}
});
}
}
}
19
View Source File : Job_AccessTrendLog_Quartz.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public async Task Run(IJobExecutionContext context)
{
// 可以直接获取 JobDetail 的值
var jobKey = context.JobDetail.Key;
var jobId = jobKey.Name;
// 也可以通过数据库配置,获取传递过来的参数
JobDataMap data = context.JobDetail.JobDataMap;
var lastestLogDatetime = (await _accessTrendLogServices.Query(null, d => d.UpdateTime, false)).FirstOrDefault()?.UpdateTime;
if (lastestLogDatetime == null)
{
lastestLogDatetime = Convert.ToDateTime("2021-09-01");
}
var accLogs = GetAccessLogs().Where(d => d.User != "" && d.BeginTime.ObjToDate() >= lastestLogDatetime).ToList();
var logUpdate = DateTime.Now;
var activeUsers = (from n in accLogs
group n by new { n.User } into g
select new ActiveUserVM
{
user = g.Key.User,
count = g.Count(),
}).ToList();
foreach (var item in activeUsers)
{
var user = (await _accessTrendLogServices.Query(d => d.User != "" && d.User == item.user)).FirstOrDefault();
if (user != null)
{
user.Count += item.count;
user.UpdateTime = logUpdate;
await _accessTrendLogServices.Update(user);
}
else
{
await _accessTrendLogServices.Add(new AccessTrendLog()
{
Count = item.count,
UpdateTime = logUpdate,
User = item.user
});
}
}
// 重新拉取
var actUsers = await _accessTrendLogServices.Query(d => d.User != "", d => d.Count, false);
actUsers = actUsers.Take(15).ToList();
List<ActiveUserVM> activeUserVMs = new();
foreach (var item in actUsers)
{
activeUserVMs.Add(new ActiveUserVM()
{
user = item.User,
count = item.Count
});
}
Parallel.For(0, 1, e =>
{
LogLock.OutSql2Log("ACCESSTRENDLOG", new string[] { JsonConvert.SerializeObject(activeUserVMs) }, false, true);
});
}
See More Examples