using Time in C# console program [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am building a small program just kind of to apply some of what I've learned and see if I can push my limits to learn more. I have so far created a Character class and used a constructor to create a "character" named Dick. I have also created a number of variables and methods that when called, increment or decrement certain variables and output certain activities that Dick is involved in on the console screen. My question is whether there is a way to track time while the program is running so that I can set the time when the program is started and then keep track of it as it runs so it will adjust variables such as hunger, tiredness, time to go to work, time to leave work, and then when those variables hit certain numbers, they will call the methods such as go to work, eat, go to sleep, leave work. Basically, if I could track time some how, I could use every 5 seconds to update the variables, and then the "game" would basically run itself. Any ideas?

Here is how you could do it using the System.Diagnostics namespace:
Stopwatch time = new Stopwatch(); //Create a new Stopwatch
time.Start(); //Start The Timer
Thread.Sleep(5000); //Sleeps The Program For 5 Seconds
System.WriteLine("The Timer Is At: " + time.Elapsed); //Displays What The Timer Is At, Should Be 5 Seconds.
Once you have started your timer you can ignore the Thread.Sleep(5000); part because that was just to show that the timer counts up to 5 seconds as the program is slept for 5 seconds. After starting the timer you can go back and compare the time.Elapsed() part to check if it is a multiple of 5 and if it is then update your variables, like so:
Stopwatch time = new Stopwatch();
if (time.Elapsed % 5 == 0) { //Checks If The Remainder of The Timer When Divided By 5 Is 0.
//Change Variables Or Do Whatever Here
} else {
//Do Whatever Needs To Be Done If Timer Isn't At An Interval Of 5
}
Hope this was of some help.

Related

For loop does not finish [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
I am making a game in Unity, 2D and for the creation of levels, I have added a for loop so that a number of blocks is generated a certain number of times. The problem is that it never ends, that is, instead of ending on the game screen when the two blocks are created, it continues to generate blocks infinitely.
public void GenerateInitialBlocks()
{
for (int i = 0; i < 2; i++)
{
AddLevelBlock();
}
}
I have reset the Script in Unity because it usually gives compilation errors or crashes, but it still doesn't work. Thanks for read.
I believe the problem could be in how many times the method is called.
find where in the code the method is called (perhaps using search)
make sure it's called only once per level and not repeatedly when refreshing or repainting (scene updating methods).

How many Tasks are too many [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am working on a spaceship shooter style game. In the game there are slow moving missiles that I run on different tasks.
Task t4 = new Task(() => fireShipCannons());
They don't do much; just move a small bitmap across the screen. Usually it is a for loop with 30 iterations. The problem is that the timing is off and some tasked seem to take priority over others. I also many be important to note that to control the speed of the missiles I am using Thread.Sleep(100). Because of this slowing down, the method will run for a few seconds.
I am using c#, .net, Windows Form Application
I have spent hours thinking about how to reword this, and I think it is worded correctly. The problem I was having was broad; so yes, the question may be a bit broad. I got a great answer! Does that not indicate that the question was asked correctly?
Since you are already using Tasks (good), you can simply make them async Tasks and use await Task.Delay(time).
async Task fireShipCannons(CancellationToken ct)
{
for (int i = 0; i < distance; i++) {
await Task.Delay(100, ct);
drawBitmap(i);
}
}
This way you will not tie up 1 thread for every bullet. Most likely your tasks are currently slow because you reach the limit of your threadpool, so this should be a lot faster. But additionally, you should also check if Task.Delay has taken more than the 100 ms you suggested. If it did, draw the bullet 2 spots further instead of 1, and reschedule accordingly.
async Task fireShipCannons(CancellationToken ct)
{
var start = DateTime.Now;
while (bullet.isOnscreen) {
drawBitmap(bullet);
var sleep = (start.Add(TimeSpan.FromMilliseconds(100.0)) - DateTime.Now);
if (sleep.Milliseconds > 0) {
Task.Delay(sleep, ct);
}
iter = (int)((DateTime.Now - start).TotalMilliseconds / 100 + 0.5);
bullet.moveSteps(iter); // move it iter steps.
var start = start.AddMilliseconds(100 * it);
}
}
Lastly, it might be a good idea to not hammer your draw function with new calls for every bullet, but instead combine all bullets/changes into a single render function that calculate all changes and sends them off in one go. But that depend on how your draw function itself is implemented.
It depends on the machine and the number of threads it can support. On the other hand, I don't think that using Thread.Sleep it is a good practice, why don't you just change the distance, in pixels, that the object travels every millisecond?

How to store various time from a stopwatch and use them for calculation in c#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
if (!responseDetected)
{
responseDetected = true;
bufferedTonePlay.Stop();
responseStopWatch.Stop(); // to get the response time
TimeTakenOutput.Text = responseStopWatch.Elapsed.Seconds.ToString() + ":" + responseStopWatch.Elapsed.Milliseconds.ToString() +"seconds";
MessageBox.Show("" + TimeTakenOutput.Text); // display the various response time.
//how to continue from here? is it possible to save all this various response time into an array so that i can use them for calculation.
You could save all the entries in a List<TimeSpan>, and then add a new item when your responseStopWatch.Stop() is hit.
responseStopWatch.Stop()
elapsedTimes.Add(TimeSpan.FromTicks(responseStopWatch.Elapsed.Ticks));
When you start the timer again, you need to make sure that it is reset. You can either do a
responseStopWatch.Reset();
responseStopWatch.Start();
Or you can use
responseStopWatch.Restart(); // Stops time interval measurement, resets the elapsed time to zero, and starts measuring elapsed time.
The Stopwatch serves the time in different ways. The easiest way is to handle the ticks (even when storing to database) and then using TimeSpan.FromTicks() when creating a new TimeSpan.
A simple sample:
List<TimeSpan> elapsedTimes = new List<TimeSpan>();
Stopwatch sw = new Stopwatch();
Stopwatch sw2 = new Stopwatch();
sw.Start();
Thread.Sleep(2000); // just to get some time on our stopwatch
sw.Stop();
sw2.Start();
Thread.Sleep(1500); // just to get some time on our stopwatch
sw2.Stop();
// add timespans
TimeSpan span1 = TimeSpan.FromTicks(sw.Elapsed.Ticks);
elapsedTimes.Add(span1);
TimeSpan span2 = TimeSpan.FromTicks(sw2.Elapsed.Ticks);
elapsedTimes.Add(span2);
double seconds = elapsedTimes.Sum(x => x.TotalSeconds);
Then you can do different calculations on the list as you wish. This example contains a quick sum of seconds from each item in the list.
EDIT:
You have supplied very little code in your question, but I'll try to answer your comment.
You would need to have an instance of the List<TimeSpan> which lives throughout the test. When the section (sound) starts, you start the stopwatch. You can then have two reasons to stop the stopwatch. Either user triggered, or timeout triggered. Stop the stopwatch, and log the result with the stop reason. You should couple the timespans with a test id.

How to invoke a method based on time [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi there I am fairly new to programming in C#. How can I make use of a time stamp to control the invocation of a method?
For example, if the time stamp is under a certain number of seconds, invoke one method.
If it's over a certain period of time run, invoke another method.
Can anyone steer me in the right direction?
This is the code I'd like to use:
DateTime.Now.Second + DateTime.Now.Minute * 60;
I know how to use if and else statements. All I want to do is make the computer control when they are activated using time.
You would want to use if-else statement
// Sample usage
var seconds = DateTime.Now.Second;
var time = DateTime.Now.Second + DateTime.Now.Minute * 60;
if(time < certainNumberOfSeconds) // Sample Condition.
// Invoke a method
else
// Invoke a different method.
var secondsUntilRunSecondMethod = (WaitingInSeconds - currentTime.Seconds) % 60;
You can use secondsUntilRunSecondMethod in a timer and run the method form the timer.

Recommended way to calulate time and display to user [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Just curious as to what people think is the best way to calculate how long a search takes and then display time to user.
I am using DateTime with Timespan and also Stopwatch sw = new Stopwatch.
I think using Stopwatch is cleaner code compared to DateTime with timespan.
So I'm just curious as to what professional programmers use.
i.e
Stopwatch WebSearchTime = new Stopwatch();
WebSearchTime.Start();
code to run
WebSearchTime.Stop();
double WST = WebSearchTime.Elapsed.Seconds + (WebSearchTime.Elapsed.Milliseconds / 1000.0);
Thanks
George
Stopwatch is the proper and more accurate way to determine time of execution, than DateTime.Now with DateTime calculation.
Stopwatch Class
The Stopwatch measures elapsed time by counting timer ticks in the
underlying timer mechanism. If the installed hardware and operating
system support a high-resolution performance counter, then the
Stopwatch class uses that counter to measure elapsed time.
Otherwise, the Stopwatch class uses the system timer to measure
elapsed time. Use the Frequency and IsHighResolution fields to
determine the precision and resolution of the Stopwatch timing
implementation.
I know that use of Stopwatch is preferred way but I created code snippets to use DateTime and used to use them:
DateTime start = DateTime.Now;
//logic
System.Diagnostics.Debug.WriteLine("Comment:" + (DateTime.Now - start));
Sure if you need to aggregate results you'll have to create TimeSpan. Now I see whole lot of information being outputted while debugging.
My bad. I measured performance as VARAK suggested and it turned out that DateTime.Now takes about 0.00073ms to evaluate that could be real problem in production if you'll iterate over real big amounts of data so you should use my approach carefully.

Categories

Resources