I want to create a timer and start it and gets its value at any time in C# and I want to know what it is, depending on, for example, is it by seconds or milliseconds or so forth.
Are you looking for the Stopwatch class?
using System.Diagnostics;
// ...
var stopwatch = Stopwatch.StartNew();
// ...
var milliseconds = stopwatch.ElapsedMilliseconds;
Have you looked at Stopwatch class?
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
This is another link with some good examples:
http://www.dotnetperls.com/stopwatch
var start = Environment.TickCount;
// loop for 2 seconds
while(Environment.TickCount-start <2000)
{
Console.Write(".");
}
Console.WriteLine("done");
Related
I am looking at the code written by my colleague:
long tim = DateTime.Now.Ticks;// get current time in ticks
long startWait = tim + TimeSpan.TicksPerSecond * 15; // add 15 seconds (in ticks) to current time
while ((tim < startWait) & !_myReader.ReaderOpen) //_myReader.ReaderOpen is external device
{
Thread.Sleep(100); // sleep for 100ms
tim = DateTime.Now.Ticks;
}
For some reason, this code does not look right. It seems like putting thread to sleep and waking it up every 100ms is huge waste of CPU.
You can use a Timer to execute periodically without forcing a thread to be sitting around doing nothing for the duration of that time. it's also possible that the reader that you're using exposes some means of notifying you when things happen so that you can respond to those events without needing to poll the object.
you could also do something like this which is exactly the same thing but different
at least you can stop the loop when myReader.ReaderOpen become true, if the 100ms is important to you
using System;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
const int TimeToWait = 15;
var sw = Stopwatch.StartNew();
var mnu = new ManualResetEvent(false);
while (sw.Elapsed.Seconds <= TimeToWait)
{
Console.WriteLine(sw.ElapsedMilliseconds);
mnu.WaitOne(100);
}
Console.ReadKey();
}
}
}
My program runs a batch file in cmd.exe, after it finished I want to display a MessageBox to user saying Finished in #.## seconds,
I'm redirecting CMD output to a textbox using process.BeginOutputReadLine(), this is the code I tried:
if (e.Data == null)
{
string time = process.TotalProcessorTime.Seconds.ToString();
MessageBox.Show("Finished in " + time + " seconds");
}
It took about 7-15 seconds to complete the process, but the MessageBox displayed Finished in 0 seconds.
How do I get the accurate time it took to complete in seconds?
Stopwatch watch = new Stopwatch();
watch.Start();
//Do things
watch.Stop();
Text = watch.Elapsed.TotalSeconds.ToString();
Have you tried process.ExitTime.Subtract(process.StartTime).TotalSeconds?
Edited to add: Note that you will get an exception if you try to use this before the process has exited. Per the documentation for ExitTime, use the HasExited property if you have any doubt as to whether this is the case or not.
Could you ultimately do something like this if it makes it easier to read for you
var procTime = DateTime.Now - Process.GetCurrentProcess().StartTime;
var procTimeInSec = procTime.Seconds;
MessageBox.Show(string.Format("Finished in {0} seconds", procTimeInSec));
to access you may want to change the two `var local variables to be accessible from outside the local scope.
below is how you would declare it outside of the local method at the top of the Class
public static TimeSpan procTime = new TimeSpan();
var procTimeInSec, can still be declared in the local scope
Just basic Stopwatch should be enough.
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// run external process, if asynchronous -
//store stopWatch in member variable instead of local
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Note that TotalProcessorTime measures CPU usage time, which could very well be 0 seconds for CMD.exe as it really does not do much.
You should look into the Stopwatch class. You'll need to start the stopwatch before your process begins, then stop it afterwards and get the elapsed time.
You should use the Stopwatch class when starting the process.
On the process, add an event handler for the Exited event and when the process is done, stop the stopwatch and retrieve the time.
class Foo
{
Stopwatch watch = new Stopwatch();
public void RunProcess(Process process)
{
process.Exited += new EventHandler(ProcessExit);
process.Start();
watch.Start();
}
public void ProcessExit(object sender, EventArgs e)
{
watch.Stop();
}
}
I'm trying to write something to stop running the code after 15 seconds of running.
I don't want While loop or any kind of loop to be used and would like to use IF-ELSE conditions instead as it would make it easier for me in my code.
The part of code I want to stop being executed after 15 seconds is a FOR loop itself. Let's consider the below code for example:
for (int i = 1; i < 100000; i++)
{
Console.WriteLine("This is test no. "+ i+ "\n");
}
How would you stop this loop after 15 seconds of running?
You can assign DateTime variable before the loop having the current date and time, then in each loop iteration simply check if 15 seconds have passed:
DateTime start = DateTime.Now;
for (int i = 1; i < 100000; i++)
{
if ((DateTime.Now - start).TotalSeconds >= 15)
break;
Console.WriteLine("This is test no. "+ i+ "\n");
}
Update: while the above will usually work, it's not bullet proof and might fail on some edge cases (as Servy pointed out in a comment), causing endless loop. Better practice would be using the Stopwatch class, which is part of System.Diagnostics namespace:
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 1; i < 100000; i++)
{
if (watch.Elapsed.TotalMilliseconds >= 500)
break;
Console.WriteLine("This is test no. " + i + "\n");
}
watch.Stop();
I'm posting my answer from my older post because it's more relevant here,
I think you need to measure time and stop the code after particular time say "15 seconds" ,StopWatch class can help you out.
// Create new stopwatch instance
Stopwatch stopwatch = new Stopwatch();
// start stopwatch
stopwatch.Start();
// Stop the stopwatch
stopwatch.Stop();
// Write result
Console.WriteLine("Time elapsed: {0}",stopwatch.Elapsed);
// you can check for Elapsed property when its greater than 15 seconds
//then stop the code
Elapsed property returns TimeSpan instance you would do something like this.
TimeSpan timeGone = stopwatch.Elapsed;
To fit your scenario you can do something like this
Stopwatch stopwatch = new Stopwatch();
TimeSpan timeGone;
// Use TimeSpan constructor to specify:
// ... Days, hours, minutes, seconds, milliseconds.
// ... The TimeSpan returned has those values.
TimeSpan RequiredTimeLine = new TimeSpan(0, 0, 0, 15, 0);//set to 15 sec
While ( timeGone.Seconds < RequiredTimeLine.Seconds )
{
stopwatch.Start();
Start();
timeGone = stopwatch.Elapsed;
}
Stop();//your method which will stop listening
Some useful links
MSDN StopWatch
Better you can use below code, which would help to improve in performance.
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));
C#
I need to show the time running while the process is doing, shows the seconds increasing, normally: 00:00:01, 00:00:02, 00:00:03..... etc.
I'm using this code:
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
//here is doing my process
stopwatch.Stop();
when the process stop, I show the time ELAPSED, with this:
TimeSpan ts = stopwatch.Elapsed;
...and this:
{0} minute(s)"+ " {1} second(s)", ts.Minutes, ts.Seconds, ts.Milliseconds/10.
this show the total time elapsed, But I need show the time running in console.
How can I do this?
Try
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
Console.Write(stopwatch.Elapsed.ToString());
Console.Write('\r');
}
UPDATE
To prevent display of milliseconds:
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
TimeSpan timeSpan = TimeSpan.FromSeconds(Convert.ToInt32(stopwatch.Elapsed.TotalSeconds));
Console.Write(timeSpan.ToString("c"));
Console.Write('\r');
}
If I understand correctly, you are wanting to continually update the timespan on the console while the work is still proceeding. Is that correct? If so, you will need to either do the work in a separate thread, or update the console in a separate thread. One of the best references I've seen for threading is http://www.albahari.com/threading/.
Hope this helps.
Is there a class in C# that can give me clock ticks, seconds consumed by a method? I guess I have two wrap that functionality around function to time the ticks and seconds taken up.
You could use the System.Diagnostics.Stopwatch class.
Stopwatch sw = new Stopwatch();
sw.Start();
// Your method call here...
sw.Stop();
// Get the elapsed time
TimeSpan elapsed = sw.Elapsed;
From here, you can use the TimeSpan.Ticks or the TimeSpan.TotalSeconds properties to determine the elapsed ticks or elapsed seconds, respectively.
If you wanted to, you could use a method along the following lines to "wrap" that functionality around a function, as you mentioned (just an idea, you'd probably want to tweak this code to suit your specific purposes -- passing in arguments, etc.):
public static T ExecuteWithElapsedTime<T>(Func<T> function, out TimeSpan elapsedTime)
{
T rval;
Stopwatch sw = new Stopwatch();
sw.Start();
rval = function();
sw.Stop();
elapsedTime = sw.Elapsed;
return rval;
}
And you could call it like this (where myFunc is a function that returns an int):
TimeSpan elapsed;
int result = ExecuteWithElapsedTime(myFunc, out elapsed);
Might be simpler though to not even bother with a method like this, and just put the Stopwatch code inline with your method call.
Use:
using System.Diagnostics;
...
var sw = Stopwatch.StartNew();
DoYaThing();
Console.WriteLine("{0} Elapsed", sw.Elapsed);
There's the high resolution timer ...
Also, iirc a TimeSpan can give you a measurement in ticks back.
You can check out the [System.TimeSpan] class and wrap that around your method.