Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to write a timer in C/C++?

Tags:

c++

c

What is the simplest way to write a timer in C/C++?

Hi,

What is the simplest way to write a timer, say in C/C++? Previously I used a for loop and a do-while loop. I used the for loop as a counter and the do-while loop as a comparison for "end of time". The program worked as I wanted it to, but consumed too much system resources.

I'm looking for the simplest way to write a timer.

Thank you!

EDIT:

The program works on a set of servers both Linux and Windows, so it's a multiplatform environment. I dont want to use the unsleep or sleep function as I'm trying to write everything from scratch.

The nature of the program: The program counts power time and battery time on systems.

EDIT2:

OK, it seems that this caused some confusion so I'm going to try to explain what I have done so far. I've created a program that runs in the background and powers off the system if it's idle for a certain amount of time, it also checks for the battery life on a specific system and goes to stand by mode if the system has been running on battery for a while. I input the time manually so I need a timer. I want to write it from scratch as it's a part of a personal project I've been working on.

like image 944
Secko Avatar asked Jul 08 '09 10:07

Secko


2 Answers

Your best bet is to use an operating system primitive that suspends the program for a given amount of time (like Sleep() in Windows). The environment where the program will run will most likely have some mechanism for doing this or similar thing. That's the only way to avoid polling and consuming CPU time.

like image 146
sharptooth Avatar answered Nov 15 '22 10:11

sharptooth


If you just want your program to wait a certain amount of time, you can use:

  • Sleep (in Windows)
  • usleep (in Unix)
  • boost::this_thread::sleep (everywhere)

If you wish to process or display the time going up until elapsed, your approach of using a while() loop is fine, but you should add a small sleep (20ms, for example, but ultimately that depends on the precision you require) in the while loop, as not to hog the CPU.

like image 25
small_duck Avatar answered Nov 15 '22 12:11

small_duck