我的代码如下:
#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);
}
我正在编译
g ++ -W -Wall -Wno-unknown-pragmas -Wpointer-arith -Wcast-align -Wcast-qual -Wsign-compare -Wconversion -O -fno-strict-aliasing
我有一些警告,我需要消除。怎么样?
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
答案 0 :(得分:3)
如果你不真的需要将值四舍五入到最接近的毫秒 - 也就是说,如果你可以使用高达1毫秒而不是1/2毫秒的不准确度 - 你可以简单地写
mtime = seconds * 1000 + useconds / 1000;
否则,它必须是
mtime = seconds * 1000 + (useconds / 500 + 1) / 2;
修改:是否。见评论。
答案 1 :(得分:1)
也改变它:
mtime = seconds * 1000 + useconds/1000;
差别仅在于它没有四舍五入到最接近的微秒(它向下舍入)
无论如何都没有那么准确的计时器。
如果你真的必须有额外的准确性(四舍五入到最接近而不是四舍五入到地板上)。
// Add 500 to useconds so that when we divide by 1000 we effectively
// round to nearest rather than truncate thus rounding to floor
mtime = seconds * 1000 + (useconds + 500) / 1000;
答案 2 :(得分:0)
hacky方式是施展......
mtime = (long) (((double)seconds * 1000.0 + (double)useconds/1000.0) + 0.5);
这会删除所有警告......
答案 3 :(得分:-1)
这应该有效:
mtime = (long)(((long long)seconds*1000000 + useconds + 500)/1000);
以相同的方式转换alltime
的表达式。
您看到警告的原因是您的表达式从long转换为double并返回以进行数学运算。您可以通过重新调整表达式来避免它,以完全保持在整数类型中。请注意转换为long long
以避免溢出(谢谢,尼克)。
编辑您可以进一步简化此操作并取消转换:
mtime = seconds*1000 + (useconds + 500)/1000;