The result that is printed is always zero (0.00) and I want to know what I am doing wrong.
The first function returns the beginning time and the second the final time.
#include <sys/time.h>
#include <time.h>
void getTime(struct timeval begin){
gettimeofday(&(begin), (struct timezone*) 0);
}
float elapTime(struct timeval begin, struct timeval end){
return (1e+6*((end).tv_sec - (begin).tv_sec) + ((end).tv_usec - (begin).tv_usec));
}
int main(int argc, char **argv) {
struct timeval begin, end;
getTime(begin);
printf("Time: %.2f", elapTime(begin, end));
}
You could do something like this instead:
#include <time.h>
#include <stdio.h>
int main() {
clock_t begin, end;
int i = 1e8;
begin = clock();
while(i--);
end = clock();
printf("Time: %.2f\n", (double) (end-begin)/CLOCKS_PER_SEC);
}
The clock() function counts processor clock cycles. By dividing it by CLOCKS_PER_SEC you get seconds. The code above counts the time it takes to iterate 1e8 down to 0.
Try using more simple functions:
double floattime (void)
{
struct timeval t;
if (gettimeofday (&t, (struct timezone *)NULL) == 0)
return (double)t.tv_sec + t.tv_usec * 0.000001;
return (0);
}
int main(int argc, char **argv) {
double begin;
begin = floattime();
getchar ();
printf("Time: %.2f", floattime () - begin);
return 0;
}
And don't forget to wait some time before calculating time execution. Else, it will always return 0.00s.
Related
As mentioned in title, how can I execute the specific threads at specific time accurately?
Is there any library help to do it?
For example, [00:00:00.00, 00:05:00.00, 00:10:00.00..04:00:00.00, 04:05:00.00...]
Here is my current approach to do it, is there any better way to do it?
#include <stdio.h>
#include <unistd.h>
#include <time.h>
unsigned interval = 5*60;
void until_next_tick(time_t *last_tick){
time_t now = time(NULL);
time_t next_tick = now / interval * interval + interval;
time_t diff = next_tick - now;
usleep(diff * 1000 * 1000);
*last_tick = next_tick;
}
void print_current_time(char *str){
time_t raw = time(NULL);
struct tm *curr = localtime(&raw);
sprintf(str, "%04d/%02d/%02d %02d:%02d:%02d",
curr->tm_year+1900, curr->tm_mon+1, curr->tm_mday,
curr->tm_hour, curr->tm_min, curr->tm_sec);
}
int main(int argc, char **argv)
{
time_t last_tick = time(NULL);
char str[30];
while (1) {
print_current_time(str);
printf("%s\n", str);
until_next_tick(&last_tick);
}
return 0;
}
Use timer_create with SIGEV_THREAD and set repeating time in timer_settime to start a new thread at a repeated time interval.
One simple way is to have a while(true) loop which calls sleep(1); and then in the loop checks what time it is with time(NULL) and if the time for a thread is past due, start the corresponding thread.
One simple way is using time() to get the time:
#include <stdio.h>
#include <time.h>
void *get_sys_stat(void* arg)
{
// Do somthing hrear
}
int main()
{
hour = 5;
min = 30;
int status = 0;
time_t t = time(NULL);
pthread_t sys_stat_thread;
while(1) {
/* Get time*/
struct tm tm = *localtime(&t);
/* Trigger another process or thread */
if ((tm.tm_hour == hour) && (tm.tm_min == min))
pthread_create(&sys_stat_thread, NULL, get_sys_stat, NULL);
}
}
The function displayTimeDifference is not working properly; the issue is that the printf statement is failing. After Googling the format of the printf statement when using a timeval is correct. Not sure why I can't print out the value of the timeval. I'm not getting any system errors from gettimeofday().
#include <sys/time.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
struct timeval *timeBefore;
struct timeval *timeAfter;
char * Buffer;
double malloctest(const int, const int, const int);
double calloctest(const int, const int, const int);
double allocatest(const int, const int, const int);
void displayTimeDifference();
int main(int argc, char **argv)
{
malloctest(3072, 10, 10);
return 0;
}
double malloctest(const int objectsize, const int numobjects, const int numtests)
{
int i;
int retVal;
for (i = 1; i < numtests; i++) {
if ((retVal = gettimeofday(timeBefore, NULL)) != 0) {
printf("ERROR: gettimeofday failed with code: %d\n", retVal);
}
Buffer = (char*)malloc(objectsize * sizeof(char));
if ((retVal = gettimeofday(timeAfter, NULL)) != 0) {
printf("ERROR: gettimeofday failed with code: %d\n", retVal);
}
displayTimeDifference();
}
return 0.0;
}
void displayTimeDifference()
{
printf("Time in microseconds: %ld microseconds\n", (timeAfter->tv_sec - timeBefore->tv_sec));
}
gettimeofday needs a valid pointer to struct timeval, where it can save the informations, you call it with a NULL pointer.
you should change
struct timeval *timeBefore;
struct timeval *timeAfter;
to
struct timeval timeBefore;
struct timeval timeAfter;
and the calls to gettimeofday(&timeBefore, NULL) and gettimeofday(&timeAfter, NULL). You check the return value of this function and print something, but your program continues as it was successfully.
Also
printf("Time in microseconds: %ld microseconds\n", (timeAfter->tv_sec - timeBefore->tv_sec));
to
printf("Time in seconds: %ld microseconds\n", (timeAfter.tv_sec - timeBefore.tv_sec));.
You are only calculating the seconds, not the microseconds.
Another possibility is to malloc the memory for the pointer, but that is not really necessary.
As already said in another answer you have wrongly declared the struct timeval as pointers.
I share my timing macros:
#define START_TIMER(begin) gettimeofday(&begin, NULL) // ;
#define END_TIMER(end) gettimeofday(&end, NULL) // ;
//get the total number of sec:
#define ELAPSED_TIME(elapsed, begin, end) \
elapsed = (end.tv_sec - begin.tv_sec) \
+ ((end.tv_usec - begin.tv_usec)/1000000.0) // ;
Where you have to define the variables:
struct timeval begin, end;
double elapsed;
I am trying to create a function that compare two timestamps, if the first timestamp is earlier than the second one, the function will return -1; if equal, return 0; if later, return 1;
Below is my code, however, it does not work and throws segmentation fault (core dumped) error when I run it:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
typedef struct timeval timevalue;
int compare_time_stamps(timevalue *a, timevalue *b)
{
int cmp = timercmp(a, b, >);
if (cmp > 0)
return 1; /* a is greater than b */
else
{
cmp = timercmp(a, b, ==);
if (cmp > 0)
return 0; /* a is equal to b */
else
return -1; /* a is less than b */
}
}
int main()
{
timevalue *start, *end;
gettimeofday(start, NULL);
int i;
for (i = 0; i < 1000000; i++);
gettimeofday(end, NULL);
int cmp = compare_time_stamps(start, end);
printf("comparison result is %d\n", cmp);
return 0;
}
This being said, if I do not start with timevalue *, everything works just fine, see the working code below:
typedef struct timeval timevalue;
int compare_time_stamps(timevalue a, timevalue b)
{
int cmp = timercmp(&a, &b, >);
if (cmp > 0)
return 1; /* a is greater than b */
else
{
cmp = timercmp(&a, &b, ==);
if (cmp > 0)
return 0; /* a is equal to b */
else
return -1; /* a is less than b */
}
}
int main()
{
timevalue start, end;
gettimeofday(&start, NULL);
int i;
for (i = 0; i < 1000000; i++);
gettimeofday(&end, NULL);
int cmp = compare_time_stamps(start, end);
printf("the comparison result is %d\n", cmp);
return 0;
}
What makes the difference between these two approaches? thanks
timevalue start, end;
when you do this, you are allocating space for the struct timeval, which you have called
typedef struct timeval timevalue;
so you are actually allocating the space for the two structures in you current stack frame.
when you do timevalue *start, *end; you are only allocating two pointers to the struct timeval but no memory has been allocated to the struct timeval you would have to use malloc and allocate space.
start = malloc(sizeof(timevalue));
end = malloc(sizeof(timevalue));
also at the end of the function you have to free the malloced memory
printf("comparison result is %d\n", cmp);
free(start);
free(end);
return 0;
}
in C when you define a pointer(int *a) its your job to make sure it points to valid memory. some reading up on pointers should do.
When you use timevalue*, start is a pointer with no memory allocated to it. It will be having garbage value. Hence you get a segmentation fault.
When you use timevalue, the memory is allocated to the start variable and the time value is stored there.
the macro timbal is a struct like this:
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
so you need to allocate memory when you use "*".
I'm trying to develop a program in C that will generate a given number of random integers. It is supposed to use a given number of threads to speed this up. I found out that the regular random function won't work with threads and am now using random_r instead. I keep getting a SegFault at the initstate_r function, which doesn't make sense because I'm trying to initialize variables, not access them. Can anyone tell me what I'm doing wrong here? (The initstate_r function needs to stay in the generateRandomNumbers function.)
Here is the code:
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h> // must include stdio for pvm3.h to compile correctly
#include <sys/times.h> /* for times system call */
#include <sys/time.h> /* for gettimeofday system call */
#include <pthread.h>
/*#define DEBUG 1*/
#define RANDOM_SEED 12345678
//The main work routine
//void generateRandomNumbers(long long);
void *generateRandomNumbers(void *);
double getMilliSeconds();
/* The main work routine */
//void generateRandomNumbers(long long int count)
void *generateRandomNumbers(void *arg)
{
struct random_data buf;
int32_t result;
char rand_statebuf;
printf("hold 1\n");
// This is the function that gives me a SegFault
initstate_r(RANDOM_SEED, &rand_statebuf, 128, &buf);
printf("hold 2\n");
long long int* count = (long long int*) arg;
//printf("Count for thread ID# %ld is %lld\n", pthread_self(), *count);
long long int i;
//long int x;
srandom_r(RANDOM_SEED, &buf);
for (i = 0; i < *count; i++) {
random_r(&buf, &result);
#ifdef DEBUG
printf("%ld\n", result);
#endif
}
pthread_exit(NULL);
}
int main(int argc, char **argv)
{
long long int count, newCount;
int numThreads;
//pthread_t *tids;
double timeStart = 0;
double timeElapsed = 0;
if (argc < 3) {
fprintf(stderr, "Usage: %s <n>\n" ,argv[0]);
exit(1);
}
sscanf(argv[1],"%lld",&count); /* lld for long long int */
sscanf(argv[2],"%d",&numThreads);
pthread_t tids[numThreads];
newCount = count/numThreads;
timeStart = getMilliSeconds(); //And we are off
int i;
for (i=0; i<numThreads; i++)
{
pthread_create(&tids[i], NULL, generateRandomNumbers, (void *) &newCount);
//pthread_join(tids[i], NULL);
}
int j;
for (j=0; j<numThreads; j++)
{
pthread_join(tids[j], NULL);
}
//generateRandomNumbers(count);
printf("generated %lld random numbers\n", count);
timeElapsed = getMilliSeconds() - timeStart;
printf("Elapsed time: %lf seconds\n",(double)(timeElapsed/1000.0));
fflush(stdout);
exit(0);
}
The problem is, initstate_r's second param is supposed to be a char*,
You do:
char rand_statebuf;
printf("hold 1\n");
// This is the function that gives me a SegFault
initstate_r(RANDOM_SEED, &rand_statebuf, 128, &buf);
You pass it a pointer to 1 character which meets the requirement for a character pointer, however you need much more space than just one character. It should be:
char rand_statebuf[128];
initstate_r(RANDOM_SEED,rand_statebuf,sizeof(rand_statebuf),&buf);
How to format struct timespec to string? This structure is returned e.g. by clock_gettime() on Linux gcc:
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
One way to format it is:
printf("%lld.%.9ld", (long long)ts.tv_sec, ts.tv_nsec);
I wanted to ask the same question. Here is my current solution to obtain a string like this: 2013-02-07 09:24:40.749355372
I am not sure if there is a more straight forward solution than this, but at least the string format is freely configurable with this approach.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define NANO 1000000000L
// buf needs to store 30 characters
int timespec2str(char *buf, uint len, struct timespec *ts) {
int ret;
struct tm t;
tzset();
if (localtime_r(&(ts->tv_sec), &t) == NULL)
return 1;
ret = strftime(buf, len, "%F %T", &t);
if (ret == 0)
return 2;
len -= ret - 1;
ret = snprintf(&buf[strlen(buf)], len, ".%09ld", ts->tv_nsec);
if (ret >= len)
return 3;
return 0;
}
int main(int argc, char **argv) {
clockid_t clk_id = CLOCK_REALTIME;
const uint TIME_FMT = strlen("2012-12-31 12:59:59.123456789") + 1;
char timestr[TIME_FMT];
struct timespec ts, res;
clock_getres(clk_id, &res);
clock_gettime(clk_id, &ts);
if (timespec2str(timestr, sizeof(timestr), &ts) != 0) {
printf("timespec2str failed!\n");
return EXIT_FAILURE;
} else {
unsigned long resol = res.tv_sec * NANO + res.tv_nsec;
printf("CLOCK_REALTIME: res=%ld ns, time=%s\n", resol, timestr);
return EXIT_SUCCESS;
}
}
output:
gcc mwe.c -lrt
$ ./a.out
CLOCK_REALTIME: res=1 ns, time=2013-02-07 13:41:17.994326501
The following will return an ISO8601 and RFC3339-compliant UTC timestamp, including nanoseconds.
It uses strftime(), which works with struct timespec just as well as with struct timeval because all it cares about is the number of seconds, which both provide. Nanoseconds are then appended (careful to pad with zeros!) as well as the UTC suffix 'Z'.
Example output: 2021-01-19T04:50:01.435561072Z
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
int utc_system_timestamp(char[]);
int main(void) {
char buf[31];
utc_system_timestamp(buf);
printf("%s\n", buf);
}
// Allocate exactly 31 bytes for buf
int utc_system_timestamp(char buf[]) {
const int bufsize = 31;
const int tmpsize = 21;
struct timespec now;
struct tm tm;
int retval = clock_gettime(CLOCK_REALTIME, &now);
gmtime_r(&now.tv_sec, &tm);
strftime(buf, tmpsize, "%Y-%m-%dT%H:%M:%S.", &tm);
sprintf(buf + tmpsize -1, "%09luZ", now.tv_nsec);
return retval;
}
GCC command line example (note the -lrt):
gcc foo.c -o foo -lrt
You can pass the tv_sec parameter to some of the formatting function. Have a look at gmtime, localtime(). Then look at snprintf.
You could use a std::stringstream. You can stream anything into it:
std::stringstream stream;
stream << 5.7;
stream << foo.bar;
std::string s = stream.str();
That should be a quite general approach. (Works only for C++, but you asked the question for this language too.)