I write a simple timer function to calculate the time elapsed between start
and end
double mytimer(struct timeval *start, struct timeval *end)
{
return (end->tv_sec - start->tv_sec) + (end->tv_usec - start->tv_usec)*1e-6;
}
gcc gives the following warnings:
warning: conversion to ‘double’ from ‘__suseconds_t’ may alter its value
warning: conversion to ‘double’ from ‘__time_t’ may alter its value
Here is the definition of timeval:
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
So my question is why does C define so many incompatible types instead of simply using primitive types such as int
short
...? It's not user-friendly at all.
And how can I do arithmetic operations on these types?
Most of you seemed to have neglected my second question. What is the standard way to add two different types such as time_t
and suseconds_t
?
Because what time_t
etc contains are implementation-defined, there is nothing saying that they should contain a number of seconds as an integer, like the comment in your code implies. The reason is that they want these types to be portable between different systems.
In practice, time.h
is indeed rather cumbersome, so most of the time programs end up calling system-specific functions instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With