linux timeval gettimeofday printf error

时间:2015-10-24 14:39:30

标签: c linux time struct system-calls

函数displayTimeDifference无法正常工作;问题是printf语句失败了。在使用timeval时,使用Google搜索printf语句的格式是正确的。不知道为什么我不能打印出timeval的值。我没有从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));
}

2 个答案:

答案 0 :(得分:3)

gettimeofday需要一个指向struct timeval的有效指针,它可以保存信息,用NULL指针调用它。

你应该改变

struct timeval *timeBefore;
struct timeval *timeAfter;

struct timeval timeBefore;
struct timeval timeAfter;

以及对gettimeofday(&timeBefore, NULL)gettimeofday(&timeAfter, NULL)的来电。检查此函数的返回值并打印一些内容,但程序会继续成功。

另外
printf("Time in microseconds: %ld microseconds\n", (timeAfter->tv_sec - timeBefore->tv_sec));

printf("Time in seconds: %ld microseconds\n", (timeAfter.tv_sec - timeBefore.tv_sec));
您只计算秒数,而不是微秒。

另一种可能性是malloc指针的内存,但这不是必需的。

答案 1 :(得分:1)

正如在另一个回答中已经说过的那样,你错误地将struct timeval声明为指针。 我分享我的计时宏:

theLabel.hidden = !theLabel.hidden

您必须定义变量:

#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) // ;