c - linux timeval gettimeofday printf 错误

标签 c linux time struct system-calls

函数displayTimeDifference无法正常工作;问题是 printf 语句失败。谷歌搜索后,使用 timeval 时 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));
}

最佳答案

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

你应该改变

struct timeval *timeBefore;
struct timeval *timeAfter;

struct timeval timeBefore;
struct timeval timeAfter;

以及对 gettimeofday(&timeBefore, NULL)gettimeofday(&timeAfter, NULL) 的调用。您检查该函数的返回值并打印一些内容,但您的程序仍像成功一样继续运行。

还有
printf("以微秒为单位的时间:%ld 微秒\n", (timeAfter->tv_sec - timeBefore->tv_sec));

printf("时间以秒为单位:%ld 微秒\n", (timeAfter.tv_sec - timeBefore.tv_sec));
您只计算秒,而不计算微秒。

另一种可能性是为指针malloc内存,但这并不是真正必要的。

关于c - linux timeval gettimeofday printf 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33319392/

相关文章:

C++ 链接器错误 undefined reference to a class definition and its member functions on Linux

c++ - 从 struct timespec 转换为 std::chrono::?

javascript - 计算Javascript中两个纪元时间戳之间的秒数差异

c - Microchip 射频调制器问题

c - 如何将指针传递到 OpenCV 中的 cv BoundingRect() 中?

linux curlftpfs,带符号的密码

c++ - 在 c/c++ 中使用函数 system() 调用管道传输到 where 的 gdb,以记录堆栈跟踪 - 在 fd 0 上检测到错误挂断

c - 关于在 C 中获取用户输入的查询

c - 重定向 C 内存泄漏中的指针

datetime - 将 MySQL 日期时间字符串转换为 time.Time 格式