How can I print values in C at intervals of 1 sec? - c

I am trying to build a traffic light simulator which requires that I print green for the first 8 seconds at 1 second intervals, yellow for the next 4 seconds at 1 second intervals and red for the last 8 seconds at 1 second intervals. How can I use time.h to implement this in C?
This is my attempt, but I only get an output that prints green nonstop at intervals which are not 1 second long.
// Traffic light simul`ator
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t start, end;
double elapsed;
time(&start); /* start the timer */
do {
time(&end);
elapsed = difftime(end, start);
if (elapsed )
{
printf("green");
}
} while(elapsed < 9);
}

The following seems to work as intended:
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t start, end;
double elapsed, prev_elapsed = 0.0;
time(&start); /* start the timer */
do
{
time(&end);
elapsed = difftime(end, start);
if (elapsed >= prev_elapsed+1.0)
{
printf("green\n");
prev_elapsed = elapsed;
}
} while(elapsed < 9.0);
}
Here we keep track of the 'current' elapsed time, and the time when the previous one-second tick was noted. When this 'current' elapsed differs from the "previous" elapsed we know that one second (or, more likely, slightly more) has gone by, and we print "green".

Your code will just print "green" as fast as it can because if(elapsed) will always happen because the condition is always True. You can use difftime but will need to re-work your code a bit (I think it is adding maybe 2-3 lines). Is there a reason you can't just use sleep? It seems to be a simpler solution: print "green", call sleep(1), repeat 7 more times, move on to printing "yellow", and so on. Hope this helps!
Edit: if(elapsed) is True as long as the value elapsed is not equal to 0, and just because computers don't act instantaneously there will always be a non-zero time difference returned by difftime.

Okay, so I figured out what is going on here.
difftime() returns double. That means, fractional seconds can be returned. If they are (which they probably will be), then that means you have some value in elapsed, which means it will not evaluate to false--even though 1 full second has not yet passed.
If you want elapsed to be greater than 1, then just check for it:
if (elapsed >= 1)
{
printf("green");
}
That should do the trick.

Related

Measure time for sending a file via socket in C [duplicate]

What is the method to use a timer in C? I need to wait until 500 ms for a job. Please mention any good way to do this job. I used sleep(3); But this method does not do any work in that time duration. I have something that will try until that time to get any input.
Here's a solution I used (it needs #include <time.h>):
int msec = 0, trigger = 10; /* 10ms */
clock_t before = clock();
do {
/*
* Do something to busy the CPU just here while you drink a coffee
* Be sure this code will not take more than `trigger` ms
*/
clock_t difference = clock() - before;
msec = difference * 1000 / CLOCKS_PER_SEC;
iterations++;
} while ( msec < trigger );
printf("Time taken %d seconds %d milliseconds (%d iterations)\n",
msec/1000, msec%1000, iterations);
You can use a time_t struct and clock() function from time.h.
Store the start time in a time_t struct by using clock() and check the elapsed time by comparing the difference between stored time and current time.
Yes, you need a loop. If you already have a main loop (most GUI event-driven stuff does) you can probably stick your timer into that. Use:
#include <time.h>
time_t my_t, fire_t;
Then (for times over 1 second), initialize your timer by reading the current time:
my_t = time(NULL);
Add the number of seconds your timer should wait and store it in fire_t. A time_t is essentially a uint32_t, you may need to cast it.
Inside your loop do another
my_t = time(NULL);
if (my_t > fire_t) then consider the timer fired and do the stuff you want there. That will probably include resetting it by doing another fire_t = time(NULL) + seconds_to_wait for next time.
A time_t is a somewhat antiquated unix method of storing time as the number of seconds since midnight 1/1/1970 but it has many advantages. For times less than 1 second you need to use gettimeofday() (microseconds) or clock_gettime() (nanoseconds) and deal with a struct timeval or struct timespec which is a time_t and the microseconds or nanoseconds since that 1 second mark. Making a timer works the same way except when you add your time to wait you need to remember to manually do the carry (into the time_t) if the resulting microseconds or nanoseconds value goes over 1 second. Yes, it's messy. See man 2 time, man gettimeofday, man clock_gettime.
sleep(), usleep(), nanosleep() have a hidden benefit. You see it as pausing your program, but what they really do is release the CPU for that amount of time. Repeatedly polling by reading the time and comparing to the done time (are we there yet?) will burn a lot of CPU cycles which may slow down other programs running on the same machine (and use more electricity/battery). It's better to sleep() most of the time then start checking the time.
If you're trying to sleep and do work at the same time you need threads.
May be this examples help to you
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
/*
Implementation simple timeout
Input: count milliseconds as number
Usage:
setTimeout(1000) - timeout on 1 second
setTimeout(10100) - timeout on 10 seconds and 100 milliseconds
*/
void setTimeout(int milliseconds)
{
// If milliseconds is less or equal to 0
// will be simple return from function without throw error
if (milliseconds <= 0) {
fprintf(stderr, "Count milliseconds for timeout is less or equal to 0\n");
return;
}
// a current time of milliseconds
int milliseconds_since = clock() * 1000 / CLOCKS_PER_SEC;
// needed count milliseconds of return from this timeout
int end = milliseconds_since + milliseconds;
// wait while until needed time comes
do {
milliseconds_since = clock() * 1000 / CLOCKS_PER_SEC;
} while (milliseconds_since <= end);
}
int main()
{
// input from user for time of delay in seconds
int delay;
printf("Enter delay: ");
scanf("%d", &delay);
// counter downtime for run a rocket while the delay with more 0
do {
// erase the previous line and display remain of the delay
printf("\033[ATime left for run rocket: %d\n", delay);
// a timeout for display
setTimeout(1000);
// decrease the delay to 1
delay--;
} while (delay >= 0);
// a string for display rocket
char rocket[3] = "-->";
// a string for display all trace of the rocket and the rocket itself
char *rocket_trace = (char *) malloc(100 * sizeof(char));
// display trace of the rocket from a start to the end
int i;
char passed_way[100] = "";
for (i = 0; i <= 50; i++) {
setTimeout(25);
sprintf(rocket_trace, "%s%s", passed_way, rocket);
passed_way[i] = ' ';
printf("\033[A");
printf("| %s\n", rocket_trace);
}
// erase a line and write a new line
printf("\033[A");
printf("\033[2K");
puts("Good luck!");
return 0;
}
Compile file, run and delete after (my preference)
$ gcc timeout.c -o timeout && ./timeout && rm timeout
Try run it for yourself to see result.
Notes:
Testing environment
$ uname -a
Linux wlysenko-Aspire 3.13.0-37-generic #64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
$ gcc --version
gcc (Ubuntu 4.8.5-2ubuntu1~14.04.1) 4.8.5
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Running loop for fixed time: Counter returns different number on every run

I'm trying to run a loop for a particular period of time. During that period set a counter variable and increment it by 1. The goal is to see what is the final value of the counter variable during the run. I'm hoping to get the same counter value for the same running period. Seems like it is not the case. When I'm running the same loop with the same duration, the counter variable is returning a different number every time. I'm borrowing this code from isayme.
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main(void)
{
time_t endwait;
time_t start = time(NULL);
time_t seconds = 1; // end loop after this time has elapsed
endwait = start + seconds;
int counter =0;
while (1){
if (start < endwait){
counter=counter+1;
start = time(NULL);
}
else
break;
}
printf("Counter Value: %d", counter);
return 0;
}
output on different run:
Counter Value: 99742750
Counter Value: 30134682
Counter Value: 30596672
So, my question is
How can I get the same counter variable for a fixed loop-time?
I was trying to set the variable seconds less than 1, but it yields 0. So, How can I set this time in fractions?
Thank you in advance.
On a POSIX system the time() function returns time measured in seconds:
The time() function shall return the value of time in seconds since the Epoch.
Windows is similar:
Returns the time as seconds elapsed since midnight, January 1, 1970, or -1 in the case of an error.
The first call to time() in your process happens at effectively a random moment within a single second, and then your loop runs until the return value from time() changes.
As such, your loop will run some random length of time between some very small fraction of one second all the way to about a full second. The very first call to time() in your loop can return a value that causes your loop to end, or your loop may run for about a full second. Or any length of time in between.
That's assuming nothing else is running on your computer. That can and will also change your results.

Run code for exactly one second

I would like to know how I can program something so that my program runs as long as a second lasts.
I would like to evaluate parts of my code and see where the time is spend most so I am analyzing parts of it.
Here's the interesting part of my code :
int size = 256
clock_t start_benching = clock();
for (uint32_t i = 0;i < size; i+=4)
{
myarray[i];
myarray[i+1];
myarray[i+2];
myarray[i+3];
}
clock_t stop_benching = clock();
This just gives me how long the function needed to perform all the operations.
I want to run the code for one second and see how many operations have been done.
This is the line to print the time measurement:
printf("Walking through buffer took %f seconds\n", (double)(stop_benching - start_benching) / CLOCKS_PER_SEC);
A better approach to benchmarking is to know the % of time spent on each section of the code.
Instead of making your code run for exactly 1 second, make stop_benchmarking - start_benchmarking the total run time - Take the time spent on any part of the code and divide by the total runtime to get a value between 0 and 1. Multiply this value by 100 and you have the % of time consumed at that specific section.
Non-answer advice: Use an actual profiler to profile the performance of code sections.
On *nix you can set an alarm(2) with a signal handler that sets a global flag to indicate the elapsed time. The Windows API provides something similar with SetTimer.
#include <unistd.h>
#include <signal.h>
int time_elapsed = 0;
void alarm_handler(int signal) {
time_elapsed = 1;
}
int main() {
signal(SIGALRM, &alarm_handler);
alarm(1); // set alarm time-out to 1 second
do {
// stuff...
} while (!time_elapsed);
return 0;
}
In more complicated cases you can use setitimer(2) instead of alarm(2), which lets you
use microsecond precision and
choose between counting
wall clock time,
user CPU time, or
user and system CPU time.

timestamp in c with milliseconds precision

I'm relatively new to C programming and I'm working on a project which needs to be very time accurate; therefore I tried to write something to create a timestamp with milliseconds precision.
It seems to work but my question is whether this way is the right way, or is there a much easier way? Here is my code:
#include<stdio.h>
#include<time.h>
void wait(int milliseconds)
{
clock_t start = clock();
while(1) if(clock() - start >= milliseconds) break;
}
int main()
{
time_t now;
clock_t milli;
int waitMillSec = 2800, seconds, milliseconds = 0;
struct tm * ptm;
now = time(NULL);
ptm = gmtime ( &now );
printf("time before: %d:%d:%d:%d\n",ptm->tm_hour,ptm->tm_min,ptm->tm_sec, milliseconds );
/* wait until next full second */
while(now == time(NULL));
milli = clock();
/* DO SOMETHING HERE */
/* for testing wait a user define period */
wait(waitMillSec);
milli = clock() - milli;
/*create timestamp with milliseconds precision */
seconds = milli/CLOCKS_PER_SEC;
milliseconds = milli%CLOCKS_PER_SEC;
now = now + seconds;
ptm = gmtime( &now );
printf("time after: %d:%d:%d:%d\n",ptm->tm_hour,ptm->tm_min,ptm->tm_sec, milliseconds );
return 0;
}
The following code seems likely to provide millisecond granularity:
#include <windows.h>
#include <stdio.h>
int main(void) {
SYSTEMTIME t;
GetSystemTime(&t); // or GetLocalTime(&t)
printf("The system time is: %02d:%02d:%02d.%03d\n",
t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
return 0;
}
This is based on http://msdn.microsoft.com/en-us/library/windows/desktop/ms724950%28v=vs.85%29.aspx. The above code snippet was tested with CYGWIN on Windows 7.
For Windows 8, there is GetSystemTimePreciseAsFileTime, which "retrieves the current system date and time with the highest possible level of precision (<1us)."
Your original approach would probably be ok 99.99% of the time (ignoring one minor bug, described below). Your approach is:
Wait for the next second to start, by repeatedly calling time() until the value changes.
Save that value from time().
Save the value from clock().
Calculate all subsequent times using the current value of clock() and the two saved values.
Your minor bug was that you had the first two steps reversed.
But even with this fixed, this is not guaranteed to work 100%, because there is no atomicity. Two problems:
Your code loops time() until you are into the next second. But how far are you into it? It could be 1/2 a second, or even several seconds (e.g. if you are running a debugger with a breakpoint).
Then you call clock(). But this saved value has to 'match' the saved value of time(). If these two calls are almost instantaneous, as they usually are, then this is fine. But Windows (and Linux) time-slice, and so there is no guarantee.
Another issue is the granularity of clock. If CLOCKS_PER_SEC is 1000, as seems to be the case on your system, then of course the best you can do is 1 msec. But it can be worse than that: on Unix systems it is typically 15 msecs. You could improve this by replacing clock with QueryPerformanceCounter(), as in the answer to timespec equivalent for windows, but this may be otiose, given the first two problems.
Clock periods are not at all guaranteed to be in milliseconds. You need to explicitly convert the output of clock() to milliseconds.
t1 = clock();
// do something
t2 = clock();
long millis = (t2 - t1) * (1000.0 / CLOCKS_PER_SEC);
Since you are on Windows, why don't you just use Sleep()?

clock_gettime on Raspberry Pi with C

I want to measure the time between the start to the end of the function in a loop. This difference will be used to set the amount of loops of the inner while-loops which does some here not important stuff.
I want to time the function like this :
#include <wiringPi.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#define BILLION 1E9
float hz = 1000;
long int nsPerTick = BILLION/hz;
double unprocessed = 1;
struct timespec now;
struct timespec last;
clock_gettime(CLOCK_REALTIME, &last);
[ ... ]
while (1)
{
clock_gettime(CLOCK_REALTIME, &now);
double diff = (last.tv_nsec - now.tv_nsec );
unprocessed = unprocessed + (diff/ nsPerTick);
clock_gettime(CLOCK_REALTIME, &last);
while (unprocessed >= 1) {
unprocessed --;
DO SOME RANDOM MAGIC;
}
}
The difference between the timer is always negative. I was told this was where the error was:
if ( (last.tv_nsec - now.tv_nsec)<0) {
double diff = 1000000000+ last.tv_nsec - now.tv_nsec;
}
else {
double diff = (last.tv_nsec - now.tv_nsec );
}
But still, my variable difference and is always negative like "-1095043244" (but the time spent during the function is a positive of course).
What's wrong?
Your first issue is that you have `last.tv_nsec - now.tv_nsec, which is the wrong way round.
last.tv_nsec is in the past (let's say it's set to 1), and now.tv_nsec will always be later (for example, 8ns later, so it's 9). In that case, last.tv_nsec - now.tv_nsec == 1 - 9 == -8.
The other issue is that tv_nsec isn't the time in nanoseconds: for that, you'd need to multiply the time in seconds by a billion and add that. So to get the difference in ns between now and last, you want:
((now.tv_sec - last.tv_sec) * ONE_BILLION) + (now.tv_nsec - last.tv_nsec)
(N.B. I'm still a little surprised that although now.tv_nsec and last.tv_nsec are both less than a billion, subtracting one from the other gives a value less than -1000000000, so there may yet be something I'm missing here.)
I was just investigating timing on Pi, with similar approach and similar problems. My thoughts are:
You don't have to use double. In fact you also don't need nano-seconds, as the clock on Pi has 1 microsecond accuracy anyway (it's the way the Broadcom did it). I suggest you to use gettimeofday() to get microsecs instead of nanosecs. Then computation is easy, it's just:
number of seconds + (1000 * 1000 * number of micros)
which you can simply calculate as unsigned int.
I've implemented the convenient API for this:
typedef struct
{
struct timeval startTimeVal;
} TIMER_usecCtx_t;
void TIMER_usecStart(TIMER_usecCtx_t* ctx)
{
gettimeofday(&ctx->startTimeVal, NULL);
}
unsigned int TIMER_usecElapsedUs(TIMER_usecCtx_t* ctx)
{
unsigned int rv;
/* get current time */
struct timeval nowTimeVal;
gettimeofday(&nowTimeVal, NULL);
/* compute diff */
rv = 1000000 * (nowTimeVal.tv_sec - ctx->startTimeVal.tv_sec) + nowTimeVal.tv_usec - ctx->startTimeVal.tv_usec;
return rv;
}
And the usage is:
TIMER_usecCtx_t timer;
TIMER_usecStart(&timer);
while (1)
{
if (TIMER_usecElapsedUs(timer) > yourDelayInMicroseconds)
{
doSomethingHere();
TIMER_usecStart(&timer);
}
}
Also notice the gettime() calls on Pi take almost 1 [us] to complete. So, if you need to call gettime() a lot and need more accuracy, go for some more advanced methods of getting time... I've explained more about it in this short article about Pi get-time calls
Well, I don't know C, but if it's a timing issue on a Raspberry Pi it might have something to do with the lack of an RTC (real time clock) on the chip.
You should not be storing last.tv_nsec - now.tv_nsec in a double.
If you look at the documentation of time.h, you can see that tv_nsec is stored as a long. So you will need something along the lines of:
long diff = end.tv_nsec - begin.tv_nsec
With that being said, only comparing the nanoseconds can go wrong. You also need to look at the number of seconds also. So to convert everything to seconds, you can use this:
long nanosec_diff = end.tv_nsec - begin.tv_nsec;
time_t sec_diff = end.tv_sec - begin.tv_sec; // need <sys/types.h> for time_t
double diff_in_seconds = sec_diff + nanosec_diff / 1000000000.0
Also, make sure you are always subtracting the end time from the start time (or else your time will still be negative).
And there you go!

Resources