首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >linux timeval gettimeofday printf错误

linux timeval gettimeofday printf错误
EN

Stack Overflow用户
提问于 2015-10-24 14:39:29
回答 2查看 1.9K关注 0票数 2

函数displayTimeDifference不能正常工作;问题是printf语句失败了。在Googling上搜索printf语句的格式后,在使用timeval时是正确的。不知道为什么我不能打印出时间的值。我不会从gettimeofday()中得到任何系统错误。

代码语言:javascript
复制
#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));
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-10-24 14:49:14

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

你应该换衣服

代码语言:javascript
复制
struct timeval *timeBefore;
struct timeval *timeAfter;

代码语言:javascript
复制
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,但这并不是真正必要的。

票数 3
EN

Stack Overflow用户

发布于 2015-10-24 14:54:09

如前所述,在另一个答案中,您错误地将struct声明为指针。我共享我的计时宏:

代码语言:javascript
复制
#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) // ;

其中必须定义变量:

代码语言:javascript
复制
struct timeval begin, end;
double elapsed;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33319392

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档