My code is the following:
#include <iostream>
#include <sys/time.h>
using namespace std;
int main(int argc, char** argv) {
if(argv[0])
argc++;
struct timeval m_timeEnd, m_timeCreate, m_timeStart;
long mtime, alltime, seconds, useconds;
gettimeofday(&m_timeStart,NULL);
sleep(3);
gettimeofday(&m_timeCreate,NULL);
sleep(1);
gettimeofday(&m_timeEnd, NULL);
seconds = m_timeEnd.tv_sec - m_timeStart.tv_sec;
useconds = m_timeEnd.tv_usec - m_timeStart.tv_usec;
mtime = (long) (((seconds) * 1000 + useconds/1000.0) + 0.5);
seconds = useconds = 0;
seconds = m_timeEnd.tv_sec - m_timeCreate.tv_sec;
useconds = m_timeEnd.tv_usec - m_timeCreate.tv_usec;
alltime = (long) (((seconds) * 1000 + useconds/1000.0) + 0.5);
printf("IN=%ld ALL=%ld milsec.\n", mtime, alltime);
}
I am compiling with
g++ -W -Wall -Wno-unknown-pragmas -Wpointer-arith -Wcast-align
-Wcast-qual -Wsign-compare -Wconversion -O -fno-strict-aliasing
and I have some warnings that I need to eliminate. How?
a1.cpp:21: warning: conversion to 'double' from 'long int' may alter its value
a1.cpp:21: warning: conversion to 'double' from 'long int' may alter its value
a1.cpp:25: warning: conversion to 'double' from 'long int' may alter its value
a1.cpp:25: warning: conversion to 'double' from 'long int' may alter its value
This should work:
Convert the expression for
alltimein the same way.The reason you see the warnings is that your expression converts from long to double and back to do the math. You can avoid it by re-shuffling your expressions a bit to stay entirely within integral types. Note the conversion to
long longto avoid overflowing (thanks, Nick).EDIT You can further simplify this and eliminate the conversion: