4

我在 C(openMP 环境)中使用 time_t 变量来保持 cpu 执行时间......我定义了一个浮点值 sum_tot_time 来对所有 cpu 的时间求和......我的意思是 sum_tot_time 是 cpu 的 time_t 值的总和。问题是打印值 sum_tot_time 它显示为整数或长整数,顺便说一下没有小数部分!

我尝试了这些方式:

  1. 将 printf sum_tot_time 作为双精度值作为双精度值
  2. printf sum_tot_time as float 是一个浮点值
  3. 将 printf sum_tot_time 作为 double 作为 time_t 值
  4. 将 printf sum_tot_time 作为浮点数作为 time_t 值
4

2 回答 2

3

在大多数平台上,分辨率time_t最多为一秒。也就是说,在大多数平台上,time_t 它将是一个整数(32 位或 64 位)值,用于计算自 1970 年 1 月 1 日(UTC)午夜以来经过的秒数,并且只能达到一秒的分辨率。

因此,time_t值的总和也只会表现出一秒的分辨率(没有小数部分,即使转换为double.)

上面已经说过,您使用什么本机或 OpenMP 调用来获取time_t您试图累积的值?

如果使用本机 *nixgetrusage()调用来rusage使用用户/内核时间填充结构(如果您的平台支持它),或者如果使用gettimeofday()来获取挂起时间,则同时使用 thetv_sectv_usecof 字段struct timeval来生成一个double值(毫秒或-通常更好的分辨率),并使用它而不是time_t在您的计算中:

struct timeval {
        time_t          tv_sec;         /* seconds */
        suseconds_t     tv_usec;        /* microseconds */
};

相应地,您可以将GetThreadTimes/GetProcessTimes用于用户/内核时间或_ftimeWindows 平台上的挂墙时间,然后组合FILETIME::dwHighDateTime/dwLowDateTime.

于 2010-04-13T15:56:00.130 回答
0

我不确定您是否可以访问标准 *nix 系统调用(或者这是否与您正在做的事情特别相关),但如果您可以使用timeval structand gettimeofday。例如,打印一个精确到小数点后六位的时间戳,它会产生一个 tcpdump 样式的时间戳(由 Steven UNP 提供

#include    "unp.h"
#include    <time.h>

char *
gf_time(void)
{
    struct timeval  tv;
    time_t          t;
    static char     str[30];
    char            *ptr;

    if (gettimeofday(&tv, NULL) < 0)
        err_sys("gettimeofday error");

    t = tv.tv_sec;  /* POSIX says tv.tv_sec is time_t; some BSDs don't agree. */
    ptr = ctime(&t);
    strcpy(str, &ptr[11]);
        /* Fri Sep 13 00:00:00 1986\n\0 */
        /* 0123456789012345678901234 5  */
    snprintf(str+8, sizeof(str)-8, ".%06ld", tv.tv_usec);

    return(str);
}
于 2010-04-13T16:41:22.063 回答