What I want to do is to spread tasks over a number of servers randomly with very little bias if possible. So far what I worked on is able to randomly spread the tasks over a different servers. The problem is that whenever I spread the tasks over the servers, it spreads the 1-3 tasks per server. The load balancing method used is Power of Two Choices. Forgive me if I get the concept wrong.
Power of Two Choices is where two random queues are chosen, where the one with the least tasks, is assigned a task. Correct me if I'm wrong.
The photo below shows my current output.
What I want is this
My main file is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C1._2
{
class Program
{
static void details(Server[] server, int num)
{
int count = 0;
for (int i = 0; i < server.Length; i++)
{
if (server[i].Tasks == num)
{
count++;
}
}
Console.WriteLine("There are " + count + " servers with " + num + " tasks.");
}
static void Main(string[] args)
{
Random rand = new Random();
int n = 256; //number of tasks
int m; //number of servers
m = 64;//Convert.ToInt32(Console.ReadLine())
Console.WriteLine("Number of servers(m): " + m);
int d = 1; //random servers to be chosen
Console.WriteLine("Number of tasks(n): " + n);
Console.WriteLine("Number of randomly selected server(d): " + d);
//Main server setup
Server[] servers = new Server[m];
for (int i = 0; i < m; i++)
{
servers[i] = new Server(i);
}
if (d == 1)
{
for (int i = 0; i < n; i++)
{
int randS = rand.Next(m);
servers[randS].Tasks++;
}
}
//Power of Two choice algorithm is here
if (d == 2)
{
for(int i = 0; i < n; i++)
{
Server s1 = servers[rand.Next(m)];
Server s2 = servers[rand.Next(m)];
if (s1.Tasks < s2.Tasks)
{
for(int j = 0; j < m; j++)
{
if (servers[j].SNo == s1.SNo)
{
servers[j].Tasks++;
}
}
}
else
{
for (int j = 0; j < m; j++)
{
if (servers[j].SNo == s2.SNo)
{
servers[j].Tasks++;
}
}
}
}
}
//Server min max
Server maxServer = new Server();
maxServer = servers[0];
for (int i = 0; i < m; i++)
{
if (maxServer.Tasks < servers[i].Tasks)
{
maxServer = servers[i];
}
}
Console.WriteLine("\nIndex of servers with most tasks: " + "[" + maxServer.SNo + "]");
Console.WriteLine("Highest number of tasks: " + maxServer.Tasks+"\n");
Server minServer = new Server();
minServer = servers[0];
for (int i = 0; i < m; i++)
{
if (minServer.Tasks > servers[i].Tasks)
{
minServer = servers[i];
}
}
Console.WriteLine("\nIndex of servers with least tasks: " + "[" + minServer.SNo + "]");
Console.WriteLine("Lowest number of tasks: " + minServer.Tasks+"\n");
//details
details(servers, 0);
details(servers, 1);
details(servers, 2);
details(servers, 3);
details(servers, 4);
details(servers, 5);
details(servers, 6);
details(servers, 7);
details(servers, 8);
details(servers, 9);
}
}
}
Accompanied Server class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C1._2
{
class Server
{
private int server_number;
private int task;
public Server()
{
this.server_number = (int)0;
this.task = 0;
}
public Server(int sn)
{
this.server_number = sn;
this.task = 0;
}
public int SNo
{
get
{
return this.server_number;
}
set
{
this.server_number = value;
}
}
public int Tasks
{
get
{
return this.task;
}
set
{
this.task = value;
}
}
}
}
Any advice on how to do so?
When you say "random... where the one with the least tasks" means to me not random. But i think that I understand what you want. So we need to select the list of items that have least tasks and chose one of this randomic.
I rewrited a part of the class Program. Let me know if is this the expected result.
class Program
{
static void Main(string[] args)
{
//Random rand = new Random();
int numberOfTasks = 256; //number of tasks
int numberOfServers; //number of servers
numberOfServers = 64;//Convert.ToInt32(Console.ReadLine())
Console.WriteLine("Number of servers(m): " + numberOfServers);
//int d = 1; //random servers to be chosen
Console.WriteLine("Number of tasks(n): " + numberOfTasks);
//Console.WriteLine("Number of randomly selected server(d): " + d);
//Main server setup
Server[] servers = new Server[numberOfServers];
for (int i = 0; i < numberOfServers; i++)
{
servers[i] = new Server(i);
}
for(int i = 0; i < numberOfTasks; i++){
var minimumTasksValue = servers.Min(x => x.Tasks);
var listOfServersToSpread = servers.Where(x => x.Tasks == minimumTasksValue).ToList();
Random rand = new Random();
var randomServer = rand.Next(0, listOfServersToSpread.Count() - 1);
listOfServersToSpread[randomServer].Tasks++;
}
//Server min max
Server maxServer = new Server();
maxServer = servers[0];
for (int i = 0; i < numberOfServers; i++)
{
if (maxServer.Tasks < servers[i].Tasks)
{
maxServer = servers[i];
}
}
Console.WriteLine("\nIndex of servers with most tasks: " + "[" + maxServer.SNo + "]");
Console.WriteLine("Highest number of tasks: " + maxServer.Tasks + "\n");
Server minServer = new Server();
minServer = servers[0];
for (int i = 0; i < numberOfServers; i++)
{
if (minServer.Tasks > servers[i].Tasks)
{
minServer = servers[i];
}
}
Console.WriteLine("\nIndex of servers with least tasks: " + "[" + minServer.SNo + "]");
Console.WriteLine("Lowest number of tasks: " + minServer.Tasks + "\n");
//details
details(servers);
Console.ReadLine();
}
static void details(Server[] server)
{
var numberOfTasksAvailable = server.Select(x => x.Tasks).Distinct().OrderBy(x => x);
foreach(var numberOfTasks in numberOfTasksAvailable)
{
Console.WriteLine("There are " + server.Count(x => x.Tasks == numberOfTasks) + " servers with " + numberOfTasks + " tasks.");
}
}
}
Updated load balancing algorithm
if (d == 2)
{
for(int i = 0; i < n; i++)
{
int a = rand.Next(m);
int b = rand.Next(m);
servers[a < b ? a : b].Tasks++;
}
}
My problem was over-complicating the code. What it does above is that it randomly chooses two random servers from the total servers available. Compares which server has the least burden/tasks, and assigns a task to it.
Related
I'm new to C# and would like some help!
I am working on some code that allows the user to find out if specific cows on his farm aren't producing enough milk.
On line 75 the if statement is supposed to print out the cows that 'are not good enough' or Tell the user that everything is OK. But instead it permanently try's to print the Bad Cows.
Console.WriteLine("How many cows are in your herd?");
int CowNum = int.Parse(Console.ReadLine());
int Temp;
double TempD;
string TempS;
int MinimumVal = 6;
int MDIR = 4;
string[] BadList = new string[CowNum];
int[] Counter = new int[CowNum];
double[] Total = new double[CowNum];
string[] Days = new string[7] {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
string[] CowID = new string[CowNum];
double[,] CowYield = new double[CowNum, 7];
Random r = new Random();
for (int n = 0; n < CowNum; n++) // Sets Cow ID's
{
Console.WriteLine("What is the ID of Cow: " + (n + 1) + "?" );
TempS = (Console.ReadLine());
CowID[n] = TempS;
}
for (int n = 0; n < CowNum; n++) // Sets the Yield of each cow to a certin day
for (int x = 0; x < Days.GetLength(0); x++)
{
Console.WriteLine("What was the Yeild for Cow: " + CowID[n] + " on " + Days[x] + "?");
TempD = double.Parse(Console.ReadLine());
CowYield[n, x] = TempD;
if (TempD < MinimumVal)
{
Counter[n] = Counter[n] + 1;
Console.WriteLine(Counter[n]);
}
//Console.WriteLine("What was the Yeild for Cow: " + CowID[n] + " on " + Days[x] + "?"); //Randomly Generated 'Saves Time'
//Temp = r.Next(0, 20);
//Console.WriteLine(Temp);
//CowYield[n, x] = Temp;
}
for (int n = 0; n < CowNum; n++)
for (int x = 0; x < Days.GetLength(0); x++)
Total[n] = Total[n] + CowYield[n, x];
for (int n = 0; n < CowNum; n++)
{
if (Counter[n] > MDIR)
{
BadList[n] = CowID[n];
Console.WriteLine("asd" + BadList[n]);
}
}
int index = Array.IndexOf(Total, Total.Max()); // Gets index of Highest producing cow
TempS = CowID[index];
Console.WriteLine("\nThe Highest producing cow is Cow: " + TempS + ". with a whopping " + Total[index] + "L of Milk!\n");
if (BadList.GetLength(0) > 0)
{
Console.WriteLine(BadList.GetLength(0));
for (int n = 0; n < BadList.GetLength(0); n++)
{
Console.WriteLine(BadList[n]);
}
}
else
{
Console.WriteLine("None of your cows had less than 6L of milk for four or more days in a row!");
}
Console.ReadLine();
}
In short your code fails beause
(For ease of all of us, heres a simplified one)
string[] thing = new string[200]
if (thing.Length>0)
{ Console.WriteLine("All wrong");}
else
{ Console.WriteLine("OK");}
Your Length of thing is always 200 because you made it that big. So output is always "All wrong"
However if you had
List<String> thing = new List<String>();
//process list here, and use thing.Add(badcow)
if (thing.Count() >0 )
{ Console.WriteLine("All wrong");}
else
{ Console.WriteLine("OK");}
then it will work because there maybe 0 entries in the list. It may produce both answers and will pick as you expected.
I have created a piece of code to create an array of 100 elements which will randomize based on the numbers from a set array. However whenever I enter "y" I am looking the array to delete the last element and add a new random element to the start and move everything in between one to the right to allow for this. However at the moment it is completely changing the array every time I enter "y". Can anyone help with this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
int[] values = { 1, 2, 3, 4, 5, 6 };
int Min = values[0];
int Max = values[5] + 1;
int w = 0 ;
int[] rndValues = new int[100];
Random rndNum = new Random();
Console.WriteLine("Random001 " + w);
for (int i = 0; i < rndValues.Length; i++)
{
rndValues[i] = rndNum.Next(Min, Max);
}
Console.WriteLine("Random " + w);
foreach(var item in rndValues)
{
Console.Write(item.ToString() + " ");
}
if (w==0)
{
Console.WriteLine(Environment.NewLine);
prob(rndValues, Min, Max,w);
Console.WriteLine(Environment.NewLine);
w++;
}
if (w>0)
{
while(true)
{
Console.WriteLine("To change elements in the array press y");
// read input
var s = Console.ReadLine();
if(s == "y")
{
//rndValues[99] = 0;
for(int i = 0; i == rndValues.Length; i++)
{
if (i != rndValues.Length)
{
rndValues[rndValues.Length-i] = rndValues[(rndValues.Length-i)-1];
}
else if (i == rndValues.Length)
{
rndValues[0] = rndNum.Next(Min, Max);
}
}
}
else
{
break;
}
prob(rndValues, Min, Max,w);
}
}
}
public static void prob(int[] rndValues, int Min, int Max, int w )
{
double[] count = new double[rndValues.Length];
//Loop through min to max and count the occurances
for (int i = Min; i <Max; i++)
{
for (int j = 0; j < rndValues.Length; j++)
{
if (rndValues[j] == i)
{
count[i] = count[i] + 1;
}
}
}
//For displaying output only
foreach(var item in rndValues)
{
Console.Write(item.ToString() + " ");
}
Console.WriteLine("W " + w);
for (int i = Min; i < Max; i++)
{
count[i] = (count[i] / rndValues.Length) * 100;
Console.WriteLine("Probability of the number " + i + " is " + count[i]);
}
}
}
}
Thanks.
I am trying to optimize a search algorithm I am using to find marked Symbols in TwinCat 3 through the ADS Interface. The question is not TwinCat related so don't get scared off yet.
The problems:
Symbols are not loaded at once. I think the TwinCatAds library use lazy loading.
Symbols have treelike structure of non-binary not balanced tree.
The solution:
You can open more than one stream to ADS. And handle the the streams in multiple threads.
The question is, I divide the first level of symbols by the number of the processor cores. So Because the tree is unbalanced some of the Threads finish faster than the others. Because of this I need a nicer solution how to divide the work between the threads.
PS: I can't use the Parallel.ForEach(). Because of the streams it results in the same or greater time amount as the single thread solution.
My test code looks looks this, it just counts all Symbols of a huge Project.
using TwinCAT.Ads;
using System.Threading;
using System.IO;
using System.Diagnostics;
using System.Collections;
namespace MultipleStreamsTest
{
class Program
{
static int numberOfThreads = Environment.ProcessorCount;
static TcAdsClient client;
static TcAdsSymbolInfoLoader symbolLoader;
static TcAdsSymbolInfoCollection[] collection = new TcAdsSymbolInfoCollection[numberOfThreads];
static int[] portionResult = new int[numberOfThreads];
static int[] portionStart = new int[numberOfThreads];
static int[] portionStop = new int[numberOfThreads];
static void Connect()
{
client = new TcAdsClient();
client.Connect(851);
Console.WriteLine("Conected ");
}
static void Main(string[] args)
{
Connect();
symbolLoader = client.CreateSymbolInfoLoader();
CountAllOneThread();
CountWithMultipleThreads();
Console.ReadKey();
}
static public void CountAllOneThread()
{
Stopwatch stopwatch = new Stopwatch();
int index = 0;
stopwatch.Start();
Console.WriteLine("Counting with one thread...");
//Count all symbols
foreach (TcAdsSymbolInfo symbol in symbolLoader)
{
index++;
}
stopwatch.Stop();
//Output
Console.WriteLine("Counted with one thred " + index + " symbols in " + stopwatch.Elapsed);
}
static public int countRecursive(TcAdsSymbolInfo symbol)
{
int i = 0;
TcAdsSymbolInfo subSymbol = symbol.FirstSubSymbol;
while (subSymbol != null)
{
i = i + countRecursive(subSymbol);
subSymbol = subSymbol.NextSymbol;
i++;
}
return i;
}
static public void countRecursiveMultiThread(object portionNum)
{
int portionNumAsInt = (int)portionNum;
for (int i = portionStart[portionNumAsInt]; i <= portionStop[portionNumAsInt]; i++)
{
portionResult[portionNumAsInt] += countRecursive(collection[portionNumAsInt][i]);//Collection Teil
}
}
static public void CountWithMultipleThreads()
{
Stopwatch stopwatch = new Stopwatch();
int sum = 0;
stopwatch.Start();
Console.WriteLine("Counting with multiple thread...");
for (int i = 0; i < numberOfThreads; i++)
{
collection[i] = symbolLoader.GetSymbols(true);
}
int size = (int)(collection[0].Count / numberOfThreads);
int rest = collection[0].Count % numberOfThreads;
int m = 0;
for (; m < numberOfThreads; m++)
{
portionStart[m] = m * size;
portionStop[m] = portionStart[m] + size - 1;
}
portionStop[m - 1] += rest;
Thread[] threads = new Thread[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++)
{
threads[i] = new Thread(countRecursiveMultiThread);
threads[i].Start(i);
Console.WriteLine("Thread #" + threads[i].ManagedThreadId + " started, fieldIndex: " + i);
}
//Check when threads finishing:
int threadsFinished = 0;
bool[] threadFinished = new bool[numberOfThreads];
int x = 0;
while (true)
{
if (threads[x].Join(10) && !threadFinished[x] )
{
Console.WriteLine("Thread #" + threads[x].ManagedThreadId + " finished ~ at: " + stopwatch.Elapsed);
threadsFinished++;
threadFinished[x] = true;
}
x++;
x = x % numberOfThreads;
if (threadsFinished == numberOfThreads) break;
Thread.Sleep(50);
}
foreach (int n in portionResult)
{
sum += n;
}
sum += collection[0].Count;
stopwatch.Stop();
//Output
Console.WriteLine("Counted with multiple threds in Collection " + sum + " symbols " + " in " + stopwatch.Elapsed);
for (int i = 0; i < numberOfThreads; i++)
{
Console.WriteLine("#" + i + ": " + portionResult[i]);
}
}
}
}
The console output:
If you trying to run the Code use TwinCat.Ads Version 4.0.17.0(that i am using). They broke something in the new version that is available with NuGet.
Make a thread pool and keep track of threads running and idling status. At each branch check if there is idling threads, if there is assign thread to sub branch.
I'm a hobby programmer.
I tried to ask this question earlier on a very unstructured way (Sorry again), now I try to ask on the proper way.
I wrote the following code that seems to work unreliably.
The code was written like this for several reasons. I know it's messy but it should still work. To explain why I wrote it like this would mean that I need to explain several weeks' of work that is quite extensive. Please accept that this is at least the least worse option I could figure out. In the below sample I removed all sections of the code that are not needed to reproduce the error.
What this program does in a nutshell:
The purpose is to check a large number of parameter combinations for a program that receives streaming data. I simulate the original process to test parameter combinations.
First data is read from files that represents recorded streaming data.
Then the data is aggregated.
Then I build a list of parameters to test for.
Finally I run the code for each parameter combination in parallel.
Inside the parallel part I calculate a financial indicator called the bollinger bands. This is a moving average with adding +/- standard deviation. This means the upper line and the lower line should only be equal when variable bBandDelta = 0. However sometimes it happens that CandleList[slot, w][ctr].bollingerUp is equal to CandleList[slot, w][ctr].bollingerDown even when bBandDelta is not 0.
As a result I don't understand how can line 277 kick in. It seems that sometimes the program fails to write to the CandleList[slot, w][ctr]. However this should not be possible because (1) I lock the list and (2) I use ConcurrentBag. Could I have some help please?
Source files are here.
The code is:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace Justfortest
{
class tick : IComparable<tick> //Data element to represent a tick
{
public string disp_name; //ticker ID
public DateTime? trd_date; //trade date
public TimeSpan? trdtim_1; //trade time
public decimal trdprc_1; //price
public int? trdvol_1; //tick volume
public int CompareTo(tick other)
{
if (this.trdprc_1 == other.trdprc_1)
{
return other.trdprc_1.CompareTo(this.trdprc_1); //Return the later item
}
return this.trdprc_1.CompareTo(other.trdprc_1); //Return the earlier item
}
}
class candle : IComparable<candle> //Data element to represent a candle and all chart data calculated on candle level
{
public int id = 0;
public DateTime? openDate;
public TimeSpan? openTime;
public DateTime? closeDate;
public TimeSpan? closeTime;
public decimal open = 0;
public decimal high = 0;
public decimal low = 0;
public decimal close = 0;
public int? volume = 0;
public decimal totalPrice = 0;
public decimal bollingerUp = 0; //Bollinger upper line
public decimal bollingerDown = 0; //Bollinger below line
public int CompareTo(candle other)
{
if (totalPrice == other.totalPrice)
{
return other.totalPrice.CompareTo(totalPrice); //Return the later item
}
return totalPrice.CompareTo(other.totalPrice); //Return the earlier item
}
}
class param : IComparable<param> //Data element represent a trade event signal
{
public int par1;
public int bollPar;
public int par2;
public int par3;
public int par4;
public int par5;
public int par6;
public decimal par7;
public decimal par8;
public decimal par9;
public decimal par10;
int IComparable<param>.CompareTo(param other)
{
throw new NotImplementedException();
}
}
class programCLass
{
void myProgram()
{
Console.WriteLine("Hello");
Console.WindowWidth = 180;
string[] sources = new string[]
{
#"C:\test\source\sourceW1.csv",
#"C:\test\source\sourceW2.csv",
};
List<candle>[] sourceCandleList = new List<candle>[sources.Count()];
List<param> paramList = new List<param>(10000000);
var csvAnalyzer = new StringBuilder();
{
List<tick>[] updatelist = new List<tick>[sources.Count()];
Console.WriteLine("START LOAD");
for (var i = 0; i < sources.Count(); i++)
{
var file = sources[i];
updatelist[i] = new List<tick>();
// ---------- Read CSV file ----------
var reader = new StreamReader(File.OpenRead(file));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
tick update = new tick();
update.disp_name = values[0].ToString();
update.trd_date = Convert.ToDateTime(values[1]);
update.trdtim_1 = TimeSpan.Parse(values[2]);
update.trdprc_1 = Convert.ToDecimal(values[3]);
update.trdvol_1 = Convert.ToInt32(values[4]);
updatelist[i].Add(update);
}
Console.WriteLine(i);
}
Console.WriteLine("END LOAD"); // All files are in the memory
// Aggreagate
Console.WriteLine("AGGREGATE START");
int tickAggr = 500;
for (var w = 0; w < sources.Count(); w++)
{
sourceCandleList[w] = new List<candle>();
List<tick> FuturesList = new List<tick>();
foreach (var update in updatelist[w])
{
tick t = new tick();
t.disp_name = update.disp_name.ToString();
t.trd_date = update.trd_date;
t.trdtim_1 = update.trdtim_1;
t.trdprc_1 = Convert.ToDecimal(update.trdprc_1);
t.trdvol_1 = update.trdvol_1;
// Add new tick to the list
FuturesList.Add(t);
if (FuturesList.Count == Math.Truncate(FuturesList.Count / (decimal)tickAggr) * tickAggr)
{
candle c = new candle();
c.openDate = FuturesList[FuturesList.Count - tickAggr].trd_date;
c.openTime = FuturesList[FuturesList.Count - tickAggr].trdtim_1;
c.closeDate = FuturesList.Last().trd_date;
c.closeTime = FuturesList.Last().trdtim_1;
c.open = FuturesList[FuturesList.Count - tickAggr].trdprc_1;
c.high = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Max().trdprc_1;
c.low = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Min().trdprc_1;
c.close = FuturesList.Last().trdprc_1;
c.volume = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Sum(tick => tick.trdvol_1);
c.totalPrice = (c.open + c.high + c.low + c.close) / 4;
sourceCandleList[w].Add(c);
if (sourceCandleList[w].Count == 1)
{
c.id = 0;
}
else
{
c.id = sourceCandleList[w][sourceCandleList[w].Count - 2].id + 1;
}
}
}
FuturesList.Clear();
}
Console.WriteLine("AGGREGATE END");
for (var i = 0; i < sources.Count(); i++)
{
updatelist[i].Clear();
}
}
Console.WriteLine("BUILD PARAMLIST");
for (int par1 = 8; par1 <= 20; par1 += 4) // parameter deployed
{
for (int bollPar = 10; bollPar <= 25; bollPar += 5) // parameter deployed
{
for (int par2 = 6; par2 <= 18; par2 += 4) // parameter deployed
{
for (int par3 = 14; par3 <= 20; par3 += 3) // parameter deployed
{
for (int par4 = 10; par4 <= 20; par4 += 5) // parameter deployed
{
for (int par5 = 4; par5 <= 10; par5 += 2) // parameter deployed
{
for (int par6 = 5; par6 <= 30; par6 += 5)
{
for (decimal par7 = 1.0005M; par7 <= 1.002M; par7 += 0.0005M)
{
for (decimal par8 = 1.002M; par8 <= 1.0048M; par8 += 0.0007M)
{
for (decimal par9 = 0.2M; par9 <= 0.5M; par9 += 0.1M)
{
for (decimal par10 = 0.5M; par10 <= 2; par10 += 0.5M)
{
param p = new param();
p.par1 = par1;
p.bollPar = bollPar;
p.par2 = par2;
p.par3 = par3;
p.par4 = par4;
p.par5 = par5;
p.par6 = par6;
p.par7 = par7;
p.par8 = par8;
p.par9 = par9;
p.par10 = par10;
paramList.Add(p);
}
}
}
}
}
}
}
}
}
}
}
Console.WriteLine("END BUILD PARAMLIST, scenarios to test:{0}", paramList.Count);
var sourceCount = sources.Count();
sources = null;
Console.WriteLine("Start building pools");
int maxThreads = 64;
ConcurrentBag<int> pool = new ConcurrentBag<int>();
List<candle>[,] CandleList = new List<candle>[maxThreads, sourceCount];
for (int i = 0; i <= maxThreads - 1; i++)
{
pool.Add(i);
for (int w = 0; w <= sourceCount - 1; w++)
{
CandleList[i, w] = sourceCandleList[w].ConvertAll(p => p);
}
}
Console.WriteLine("End building pools");
int pItemsProcessed = 0;
Parallel.ForEach(paramList,
new ParallelOptions { MaxDegreeOfParallelism = maxThreads },
p =>
{
int slot = 1000;
while (!pool.TryTake(out slot));
var bollPar = p.bollPar;
decimal bollingerMiddle = 0;
double bBandDeltaX = 0;
for (var w = 0; w < sourceCount; w++)
{
lock (CandleList[slot, w])
{
for (var ctr = 0; ctr < CandleList[slot, w].Count; ctr++)
{
CandleList[slot, w][ctr].bollingerUp = 0; //Bollinger upper line
CandleList[slot, w][ctr].bollingerDown = 0; //Bollinger below line
//Bollinger Bands Calculation
if (ctr + 1 >= bollPar)
{
bollingerMiddle = 0;
bBandDeltaX = 0;
for (int i = 0; i <= bollPar - 1; i++)
{
bollingerMiddle = bollingerMiddle + CandleList[slot, w][ctr - i].totalPrice;
}
bollingerMiddle = bollingerMiddle / bollPar; //average
for (int i = 0; i <= bollPar - 1; i++)
{
bBandDeltaX = bBandDeltaX + (double)Math.Pow(System.Convert.ToDouble(CandleList[slot, w][ctr - i].totalPrice) - System.Convert.ToDouble(bollingerMiddle), 2);
}
bBandDeltaX = bBandDeltaX / bollPar;
decimal bBandDelta = (decimal)Math.Sqrt(System.Convert.ToDouble(bBandDeltaX));
CandleList[slot, w][ctr].bollingerUp = bollingerMiddle + 2 * bBandDelta;
CandleList[slot, w][ctr].bollingerDown = bollingerMiddle - 2 * bBandDelta;
if (CandleList[slot, w][ctr].bollingerUp == CandleList[slot, w][ctr].bollingerDown)
{
Console.WriteLine("?! Items processed=" + pItemsProcessed + " bollPar=" + bollPar + " ctr=" + ctr + " bollingerMiddle=" + bollingerMiddle + " bBandDeltaX=" + bBandDeltaX + " bBandDelta=" + bBandDelta + " bollingerUp=" + CandleList[slot, w][ctr].bollingerUp + " bollingerDown=" + CandleList[slot, w][ctr].bollingerDown);
}
}
// REMOVED Further calculations happen here
}
// REMOVED Some evaluations happen here
}
}
// REMOVED Some more evaluations happen here
Interlocked.Increment(ref pItemsProcessed);
pool.Add(slot);
});
}
static void Main(string[] args)
{
var P = new programCLass();
P.myProgram();
}
}
}
Thats my code . I want to use a faster sorting algorithm maybe quick sort or comb sort. i sorted the list twice first according to arrival then to brust time.
i need help implementing a faster sorting algorithm My main mwthod
static void Main(string[] args)
{
//----------------------------------------Reading I/O File--------------------------------------
string s = Environment.CurrentDirectory.ToString(); // returns the directory of the exe file
if (File.Exists(s + #"\input.txt")) //checking if the input files exists
Console.WriteLine("File Exists");
else
{
Console.WriteLine("File Not Found");
Console.WriteLine("-----------------------------------------------------");
return;
}
Console.WriteLine("-----------------------------------------------------");
//----------------------------------------Data Into List--------------------------------------
string FileText = File.ReadAllText(s + #"\input.txt"); //reading all the text in the input file
string[] lines = FileText.Split('\n'); //splitting the lines
List<Process> processes = new List<Process>();
for (int i = 1; i < lines.Length; i++)
{
string[] tabs = lines[i].Split('\t');//splitting the tabs to get objects' variables
Process x = new Process(tabs[0], int.Parse(tabs[1]), int.Parse(tabs[2]), int.Parse(tabs[3]));//creating object
processes.Add(x);//adding object to the list
}
// ----------------------------------------Sorting The List--------------------------------------
Process temp;
for (int k = 0; k < processes.Count; k++)
{
for (int i = k + 1; i < processes.Count; i++)
{
if (processes[k].arrivalTime > processes[i].arrivalTime)
{
temp = processes[i];
processes[i] = processes[k];
processes[k] = temp;
}
}
}
int tempClock = 0;
for (int i = 0; i < processes.Count; i++)
{
if (processes[i].arrivalTime > tempClock)
tempClock = processes[i].arrivalTime;
for (int k = i + 1; k < processes.Count; k++)
{
if (processes[k].arrivalTime <= tempClock && processes[k].brust < processes[i].brust)
{
temp = processes[i];
processes[i] = processes[k];
processes[k] = temp;
}
}
tempClock += processes[i].brust;
}
Console.WriteLine("Processes After Sorting");
Console.WriteLine("-----------------------------------------------------");
Console.WriteLine("Name\tArrival\tBrust\tPriority");
for (int i = 0; i < processes.Count; i++)
{
Console.Write(processes[i].name + "\t" + processes[i].arrivalTime + "\t" + processes[i].brust + "\t" + processes[i].priority);
Console.WriteLine();
}
Console.WriteLine("-----------------------------------------------------");
//----------------------------------------Gantt Chart--------------------------------------
Console.WriteLine("Gantt Chart");
Console.WriteLine("-----------------------------------------------------");
int counter = 0;
for (int i = 0; i < processes.Count; i++)
{
Console.Write(processes[i].name + "\t");
if (processes[i].arrivalTime < counter)
printSpaces(counter);
else
{
printSpaces(processes[i].arrivalTime);
counter = processes[i].arrivalTime;
}
printHashes(processes[i].brust);
counter += processes[i].brust;
Console.WriteLine();
}
Console.WriteLine("-----------------------------------------------------");
//-----------------------------------Completing Data And final Table-------------------------
int clock = 0, totalwait = 0, totalturnAround = 0;
for (int i = 0; i < processes.Count; i++)
{
if (processes[i].arrivalTime > clock)
{
processes[i].start = processes[i].arrivalTime;
clock += processes[i].start - processes[i].arrivalTime;
clock += processes[i].brust;
}
else
{
if (i > 0)
processes[i].start = processes[i - 1].end;
clock += processes[i].brust;
}
if (processes[i].start > processes[i].arrivalTime)
processes[i].wait = processes[i].start - processes[i].arrivalTime;
else processes[i].wait = 0;
processes[i].end = processes[i].start + processes[i].brust;
processes[i].turnAround = processes[i].wait + processes[i].brust;
totalwait += processes[i].wait;
totalturnAround += processes[i].turnAround;
}
Console.WriteLine("Name\tArrival\tBrust\tStart\tEnd\tWait\tturnaround");
for (int i = 0; i < processes.Count; i++)
{
Console.Write(processes[i].name + "\t" + processes[i].arrivalTime + "\t" + processes[i].brust + "\t" + processes[i].start + "\t" + processes[i].end + "\t" + processes[i].wait + "\t" + processes[i].turnAround);
Console.WriteLine();
}
double att = 0, awt = 0;
awt = (double)totalwait / (double)processes.Count;
att = (double)totalturnAround / (double)processes.Count;
Console.WriteLine("A.W.T= {0}", awt + "\t A.T.T= " + att);
Console.ReadKey();
}
Class Process
class Process
{
public Process(string name, int arrivalTime, int brust, int priority)
{
this.name = name;
this.arrivalTime = arrivalTime;
this.brust = brust;
this.priority = priority;
}
public Process()
{
}
public string name;
public int arrivalTime;
public int brust;
public int priority;
public int wait;
public int end;
public int start;
public int turnAround;
}
I would recommend you to have look at Parallel Sort Algorithm for inspiration.
I am also assuming that you want some kind of help implementing it, which with the above solution would be something like
// The contents of processes must implement IComparable<T>
QuicksortParallelOptimised(processes, 0, processes.Count);
But do please try to state a clear question :)
Adding the definition of the IComparable interface to your process-class;
partial class Process : IComparable<Process>
{
public override int CompareTo(Process otherProcess)
{
if (this.arrivalTime == otherProcess.arrivalTime)
return this.brust.CompareTo(otherProcess.brust);
return this.arrivalTime.CompareTo(otherProcess.brust);
}
}
Doing what I've stated so far would leave you with one round of sorting, and it would also make your code a hell of a lot more readable :)
If you have any questions just ask :)