Now a days I'm practicing some programs of C#. I have an issue in this program.
I have created this program and it took 21 seconds to execute and my CPU usage is 20% and Ram usage is 1Gb max.
- static void Main(string[] args)
- {
- string str = Console.ReadLine();
- if (str == "start")
- {
- // FrameRecord(40, 140, 780, 570, 2000, "E:\\imgCH1\\", 1);
- Stopwatch sw = new Stopwatch();
- for (int i = 1; i < 200000; i++)
- {
- sw.Start();
- Console.WriteLine("Acccessed Value" + i.ToString());
- Console.WriteLine("Time " + sw.ElapsedMilliseconds);
- }
- }
- Console.Read();
- }
but when I create 2 instances of this It took 140 seconds and CPU usage is 20 % and Ram usage is 1GB max.
Can you please help me, how can I run multiple instances which will take 21 seconds but can utilize my Ram and CPU as maximum.
Bikesh SrivastavaPosted Jan 11, 2017, 6:22 AM
Afzaal Ahmad ZeeshanPosted Jan 11, 2017, 5:17 AM
Hello Sachin,
- Every program gets a share in CPU, RAM and other resources.
- C# programs have a single thread. More instances mean, more threads to work on. (This moves into the world of parallelism)
- Other programs are also working and they need some CPU time. Whenever they execute, your program will remain idle -- that counts too.
Now to explain these points to you, let me go step by step. The first thing to understand in .NET framework, is that you only get to program .NET framework, not the underlying CPU, RAM or any other hardware resource -- that is entirely the purpose of .NET framework. If you run an application, it won't be the only application using CPU, there are other programs, threads and services that require some CPU too. They will be provided some CPU time too. Thus, 21 seconds for 200000 iterations is still way too much. In most cases, (just for I/O to console) it just takes 1-5 seconds. Which makes me think, your CPU is not powerful enough. Sorry.Your code is very poorly written, let me show you,
Finally, it is not your program that decides how much CPU or RAM it requires, instead it is the .NET framework that decides this... One of the major factor toward accessing multiple CPU cores, or accessing the full CPU limit is, by having multiple threads running.
I hope my answer clears most of the confusions in your mind.