32

How can i execute the a particluar loop for specified time

Timeinsecond = 600

int time = 0;
while (Timeinsecond > time)
{
   // do something here
}

How can i set the time varaible here, if i can use the Timer object start and stop method it doesnot return me time in seconds

Regards NewDev

NewDev
  • 365
  • 1
  • 5
  • 8

7 Answers7

77

May be the following will help:

  Stopwatch s = new Stopwatch();
  s.Start();
  while (s.Elapsed < TimeSpan.FromSeconds(600)) 
  {
      //
  }

  s.Stop();
abatishchev
  • 98,240
  • 88
  • 296
  • 433
sTodorov
  • 5,435
  • 5
  • 35
  • 55
27

If you want ease of use:

If you don't have strong accuracy requirements (true millisecond level accuracy - such as writing a high frames per second video game, or similar real-time simulation), then you can simply use the System.DateTime structure:

// Could use DateTime.Now, but we don't care about time zones - just elapsed time
// Also, UtcNow has slightly better performance
var startTime = DateTime.UtcNow;

while(DateTime.UtcNow - startTime < TimeSpan.FromMinutes(10))
{
    // Execute your loop here...
}

Change TimeSpan.FromMinutes to be whatever period of time you require, seconds, minutes, etc.

In the case of calling something like a web service, displaying something to the user for a short amount of time, or checking files on disk, I'd use this exclusively.

If you want higher accuracy:

look to the Stopwatch class, and check the Elapsed member. It is slightly harder to use, because you have to start it, and it has some bugs which will cause it to sometimes go negative, but it is useful if you need true millisecond-level accuracy.

To use it:

var stopwatch = new Stopwatch();
stopwatch.Start();

while(stopwatch.Elapsed < TimeSpan.FromSeconds(5))
{
    // Execute your loop here...
}
Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
  • 9
    `DateTime.Now` is slow (about 1000ns on my machine). You should use `DateTime.UtcNow` instead because it's about 100 times faster due to not having to perform a timezone conversion. – Gabe May 10 '11 at 05:41
  • 1
    @Gabe: Good information. Thanks for teaching me something :) Editing the answer... – Merlyn Morgan-Graham May 10 '11 at 05:43
0

use Timers in c# http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

Aman
  • 1
0

It's ugly .... but you could try this:

DateTime currentTime = DateTime.Now;
DateTime future = currentTime.AddSeconds(5);
while (future > currentTime)
{
    // Do something here ....
    currentTime = DateTime.Now;
  // future = currentTime.AddSeconds(5);
}
0
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Accord.Video.FFMPEG;


namespace TimerScratchPad
{
    public partial class Form1 : Form
    {
        VideoFileWriter writer = new VideoFileWriter();
        int second = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            writer.VideoCodec = VideoCodec.H264;
            writer.Width = Screen.PrimaryScreen.Bounds.Width;
            writer.Height = Screen.PrimaryScreen.Bounds.Height;
            writer.BitRate = 1000000;
            writer.Open("D:/DemoVideo.mp4");

            RecordTimer.Interval = 40;
            RecordTimer.Start();

        }

        private void RecordTimer_Tick(object sender, EventArgs e)
        {
            Rectangle bounds = Screen.GetBounds(Point.Empty);
            using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
                }
                writer.WriteVideoFrame(bitmap);
            }

            textBox1.Text = RecordTimer.ToString();
            second ++;
            if(second > 1500)
            {
                RecordTimer.Stop();
                RecordTimer.Dispose();
                writer.Close();
                writer.Dispose();
            }
        }
    }
}
Sai Hemanth
  • 13
  • 1
  • 4
  • this code will run without consuming more system resources more and will never experience slowing system down like when you run while loop this code will take screen shots and write to video file for every 40 milliseconds i.e. 24FPS – Sai Hemanth Feb 04 '18 at 06:25
0

Create a function for starting, stopping, and elapsed time as follows:

Class CustomTimer
{ 
   private DateTime startTime;
    private DateTime stopTime;
    private bool running = false;

    public void Start() 
    {
        this.startTime = DateTime.Now;
        this.running = true;
    }

    public void Stop() 
    {
        this.stopTime = DateTime.Now;
        this.running = false;
    }

    //this will return time elapsed in seconds
    public double GetElapsedTimeSecs() 
    {
        TimeSpan interval;

        if (running) 
            interval = DateTime.Now - startTime;
        else
            interval = stopTime - startTime;

        return interval.TotalSeconds;
    }

}

Now within your foreach loop do the following:

    CustomTimer ct = new CustomTimer();
    ct.Start();
    // put your code here
    ct.Stop();   
  //timeinsecond variable will be set to time seconds for your execution.
  double timeinseconds=ct.GetElapsedTime();
jonsca
  • 10,218
  • 26
  • 54
  • 62
Vishal Patwardhan
  • 317
  • 1
  • 4
  • 15
-7

Instead of such an expensive operation I'd recommend this: It's nasty but it's better to sit than running for doing nothing heating the cpu unnecesarily, the question is may be academic.

using System.Threading;

Thread.Sleep(600000);