Calculating Time elapsed for ten users at the same time - c#

I need to capture the time taken between two button press of ten users.
I am doing like this with StopWatch.
Stopwatch stopwatch1;
Stopwatch stopwatch2;
........ Like this ten stop watches.
private void Start_Action1()
{
stopwatch1 = new Stopwatch();
stopwatch1.Start();
}
private void Stop_Action1()
{
stopwatch1.Stop();
txtTimeForAction1.Text = stopwatch.Elapsed.ToString();
}
Same code for 10 StopWatches.
NOTE: All the users will do this START-STOP action continuously. I need to record time-elapsed for each cycle separately. I am using in desktop application. All the users will use the same application.
Using 10 Stopwatch is good practice?? Is there any better way than this?

You could keep track of the starting times for every user, use one stopwatch and don't stop it after the stop action is called by one user, only when they have all stopped. I don't know if it's better practice, but it is a different way to do it.

Personally, I'd give each "user" a DateTime (StartTime) and then when the event has finished (So E.g. Key_Up) You can get the Elapsed time with:
DateTime elapsedTime = DateTime.Now - StartTime.
then use elapsedTime.Seconds or .Minutes etc. and even use elpasedTime.ToString("hh:mm:ss") to get a nicely formatted string.

I see no reason why not using stop watches. But instead of defining ten stop watches you should save them in an array or in a dictionary where each StopWatch is associated with a user.

Related

Using Stopwatch timer versus DateTime comparisons every 1 second?

Imagine we have a dedicated OS thread, that must do something every 4.30 minutes.
You cannot suspend the thread, because it needs to check/do other things, nor can you use await/async, because that would cause the command to drop out of the dedicated OS thread, defeating the purpose of first creating one.
To solve the problem above, I found 2 solutions:
Use System.Diagnostics.Stopwatch to start a new Stopwatch object, and compare it every 1 second if it reached the desired time-frame: if (timer.ElapsedMilliseconds == 258000) { ...}
Use System.DateTime to initialize a DateTime object DateTime.UtcNow.AddMinutes(4.30) and compare that to the current date every 1 second: if (DateTime.UtcNow >= initializedDate) { ... }
First approach uses a Stopwatch. I think the Stopwatch uses a thread to do all the work, which is why I wanted to avoid it?
The second approach uses a lot of DateTime objects. Every 1 second we'd be constructing a new DateTime object of the current date.
The two solutions are equivalent unless you want very high precision: Stopwatch will use a high precision system timer if available and falls back to DateTime if not. To address your concerns:
Stopwatch does NOT use a separate thread. It just reads the system ticks (high or low precision) and does some math for you.
DateTime is a struct so creating a new instance every second should be cheap and put zero pressure on the GC.
I'd use the Stopwatch because it gives me the elapsed time for free. :)

Get milliseconds passed

A just need a stable count of the current program's progression in milliseconds in C#. I don't care about what timestamp it goes off of, whether it's when the program starts, midnight, or the epoch, I just need a single function that returns a stable millisecond value that does not change in an abnormal manner besides increasing by 1 each millisecond. You'd be surprised how few comprehensive and simple answers I could find by searching.
Edit: Why did you remove the C# from my title? I'd figure that's a pretty important piece of information.
When your program starts create a StopWatch and Start() it.
private StopWatch sw = new StopWatch();
public void StartMethod()
{
sw.Start();
}
At any point you can query the Stopwatch:
public void SomeMethod()
{
var a = sw.ElapsedMilliseconds;
}
If you want something accurate/precise then you need to use a StopWatch, and please read Eric Lippert's Blog (formerly the Principal Developer of the C# compiler Team) Precision and accuracy of DateTime.
Excerpt:
Now, the question “how much time has elapsed from start to finish?” is a completely different question than “what time is it right now?” If the question you want to ask is about how long some operation took, and you want a high-precision, high-accuracy answer, then use the StopWatch class. It really does have nanosecond precision and accuracy that is close to its precision.
If you don't need an accurate time, and you don't care about precision and the possibility of edge-cases that cause your milliseconds to actually be negative then use DateTime.
Do you mean DateTime.Now? It holds absolute time, and subtracting two DateTime instances gives you a TimeSpan object which has a TotalMilliseconds property.
You could store the current time in milliseconds when the program starts, then in your function get the current time again and subtract
edit:
if what your going for is a stable count of process cycles, I would use processor clocks instead of time.
as per your comment you can use DateTime.Ticks, which is 1/10,000 of a millisecond per tick
Also, if you wanted to do the time thing you can use DateTime.Now as your variable you store when you start your program, and do another DateTime.Now whenever you want the time. It has a millisecond property.
Either way DateTime is what your looking for
It sounds like you are just trying to get the current date and time, in milliseconds. If you are just trying to get the current time, in milliseconds, try this:
long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

I need to display the running time which will start with 0

I need to display the time which will start with 0 and (which will keep running in seconds)
I need to display in a game so it will show elapsed time when playing.
as shown in the screenshot:
someone told me to do this way,
Stopwatch st = new Stopwatch();
st.Start();
and display it with
Console.WriteLine(st.Elapsed);
but its not working (seconds are not running)!
it showing as:
As I understand you just need to update your display every 1 second so why not just use a Timer which will run every 1 second and increment whatever you display on the screen. (Read about Timer here: http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx)
You can find an example here:
How to set timer in C#?
If it's a game, there must be the animation (game) loop somewhere. You should put
Console.WriteLine(st.Elapsed);
there. This way it is going to refresh correctly.
Given this is a console game: Have the Elapsed time from the StopWatch stored in a TimeSpan and then just use the Thread.Sleep(); property from System.Threading(); to simulate 1 second.
Stopwatch st = new Stopwatch();
st.Start();
while (true)
{
TimeSpan ts = st.Elapsed;
string time = String.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds);
Console.Write("\r{0} ", time);
Thread.Sleep(1000);
}
PS: This is my first answer in this website and I hope I was helpful!

How to make a stopwatch windows form application

I am currently trying to make a chronometer in c# using the timespan class. So far I have been able to appropriately start, pause, and stop the chronometer, but I have been asked to make a lap button that registers the time in the chronometer upon click, and make another button that opens another form to list said lap times. It is this part that i have trouble with.
Basically I need help with registering the time and retaining those values to later show them in a list. I appreciate your time and willingness to help.
This is some of the code i tried to make for registering the time along with making a different class called LapList, it didnt go very well.
private void button2_Click(object sender, EventArgs e)
{
TimeSpan Et = Crono.Elapsed;
TimeSpan LapTime = Et - LastBreakTime;
LastBreakTime = Et;
++Lapcount;
LapList.getTimeSpan().Add(LapTime);
}
Thanks again for your time.
It seems you should be able to store the DateTime.Now of each click of the Lap button, then use DateTime2 - DateTime1 to give you a TimeSpan object that can be displayed?
So each click of Lap button effectively performs a List.Add(DateTime.Now) and your lap display iterates over the list, performing List[I] - List[I-1]
.NET already has a Stopwatch for measuring time and returning the elapsed time as a TimeSpan, Milliseconds or Ticks.
You can start a new Stopwatch with Stopwatch.StartNew and store the instance in a field until you need to check the elapsed time. You can also pass the instance from method to method, or store it in an array or dictionary so you can time multiple executions

How would I go about implementing a stopwatch with different speeds?

Ideally I would like to have something similar to the Stopwatch class but with an extra property called Speed which would determine how quickly the timer changes minutes. I am not quite sure how I would go about implementing this.
Edit
Since people don't quite seem to understand why I want to do this. Consider playing a soccer game, or any sport game. The halfs are measured in minutes, but the time-frame in which the game is played is significantly lower i.e. a 45 minute half is played in about 2.5 minutes.
Subclass it, call through to the superclass methods to do their usual work, but multiply all the return values by Speed as appropriate.
I would use the Stopwatch as it is, then just multiply the result, for example:
var Speed = 1.2; //Time progresses 20% faster in this example
var s = new Stopwatch();
s.Start();
//do things
s.Stop();
var parallelUniverseMilliseconds = s.ElapsedMilliseconds * Speed;
The reason your simple "multiplication" doesn't work is that it doesn't speeding up the passing of time - the factor applies to all time that has passed, as well as time that is passing.
So, if you set your speed factor to 3 and then wait 10 minutes, your clock will correctly read 30 minutes. But if you then change the factor to 2, your clock will immediately read 20 minutes because the multiplication is applied to time already passed. That's obviously not correct.
I don't think the stopwatch is the class you want to measure "system time" with. I think you want to measure it yoruself, and store elapsed time in your own variable.
Assuming that your target project really is a game, you will likely have your "game loop" somewhere in code. Each time through the loop, you can use a regular stopwatch object to measure how much real-time has elapsed. Multiply that value by your speed-up factor and add it to a separate game-time counter. That way, if you reduce your speed factor, you only reduce the factor applied to passing time, not to the time you've already recorded.
You can wrap all this behaviour into your own stopwatch class if needs be. If you do that, then I'd suggest that you calculate/accumulate the elapsed time both "every time it's requested" and also "every time the factor is changed." So you have a class something like this (note that I've skipped field declarations and some simple private methods for brevity - this is just a rough idea):
public class SpeedyStopwatch
{
// This is the time that your game/system will run from
public TimeSpan ElapsedTime
{
get
{
CalculateElapsedTime();
return this._elapsedTime;
}
}
// This can be set to any value to control the passage of time
public double ElapsedTime
{
get { return this._timeFactor; }
set
{
CalculateElapsedTime();
this._timeFactor = value;
}
}
private void CalculateElapsedTime()
{
// Find out how long (real-time) since we last called the method
TimeSpan lastTimeInterval = GetElapsedTimeSinceLastCalculation();
// Multiply this time by our factor
lastTimeInterval *= this._timeFactor;
// Add the multiplied time to our elapsed time
this._elapsedTime += lastTimeInterval;
}
}
According to modern physics, what you need to do to make your timer go "faster" is to speed up the computer that your software is running one. I don't mean the speed at wich it performs calculations, but the physical speed. The close you get to the speed of light ( the constant C ) the greater the rate at which time passes for your computer, so as you approach the speed of light, time will "speed up" for you.
It sounds like what you might actually be looking for is an event scheduler, where you specify that certain events must happen at specific points in simulated time and you want to be able to change the relationship between real time and simulated time (perhaps dynamically). You can run into boundary cases when you start to change the speed of time in the process of running your simulation and you may also have to deal with cases where real time takes longer to return than normal (your thread didn't get a time slice as soon as you wanted, so you might not actually be able to achieve the simulated time you're targeting.)
For instance, suppose you wanted to update your simulation at least once per 50ms of simulated time. You can implement the simulation scheduler as a queue where you push events and use a scaled output from a normal Stopwatch class to drive the scheduler. The process looks something like this:
Push (simulate at t=0) event to event queue
Start stopwatch
lastTime = 0
simTime = 0
While running
simTime += scale*(stopwatch.Time - lastTime)
lastTime = stopwatch.Time
While events in queue that have past their time
pop and execute event
push (simulate at t=lastEventT + dt) event to event queue
This can be generalized to different types of events occurring at different intervals. You still need to deal with the boundary case where the event queue is ballooning because the simulation can't keep up with real time.
I'm not entirely sure what you're looking to do (doesn't a minute always have 60 seconds?), but I'd utilize Thread.Sleep() to accomplish what you want.

Categories

Resources