gpt4 book ai didi

时序测量的困惑

转载 作者:太空宇宙 更新时间:2023-11-03 23:58:33 34 4
gpt4 key购买 nike

我的任务是实现三个不同的函数 get_current_time_seconds1、2 和 3,然后必须估计各种函数的分辨率。我如何估计这个?

您建议使用哪种计时功能?当我必须使用 gcc -O0 -lrt timing.c -o timing 进行编译时,编译器选项 -O0 -lrt 意味着什么?

#define BILLION 1000000000L

#define LIMIT_I 1000
#define LIMIT_J 1000

double get_current_time_seconds1()
{
/* Get current time using gettimeofday */
time_t t = time(NULL);
struct tm *tm = localtime(&t);
printf("%s\n", asctime(tm));
return (double) tm;
}

double get_current_time_seconds2()
{
struct timespec start,stop;
clock_gettime(CLOCK_REALTIME, &start);
clock_gettime(CLOCK_REALTIME, &stop);
double x = (stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec);

printf("%lf\n", x);

return (double) x;
}

double get_current_time_seconds3()
{
uint64_t diff;

struct timespec start, end;

clock_gettime(CLOCK_MONOTONIC, &start);
sleep(5);
clock_gettime(CLOCK_MONOTONIC, &end);

diff = BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
printf("elapsed time = %llu nanoseconds\n", (long long unsigned int)diff);

return (double) diff;
}

最佳答案

How would I estimate this? Which timing function would you suggest to use?

如果你想得到各种计时元素的分辨率(精度),你可以使用clock_getres函数,传入各种CLOCK_ id类型,例如:

#include <stdio.h>
#include <time.h>

static void printres(clockid_t id)
{
struct timespec ts;
int rc = clock_getres(id, &ts);
printf("clock id: %d\n", (unsigned int)id);
if (rc != 0) {
printf("Error: %d\n", rc);
return;
}
printf("tv_sec = %lu\ntv_nsec = %lu\n", ts.tv_sec, ts.tv_nsec);
}

int main(int argc, char** argv)
{
printres(CLOCK_REALTIME);
printres(CLOCK_MONOTONIC);
printres(CLOCK_PROCESS_CPUTIME_ID);
printres(CLOCK_THREAD_CPUTIME_ID);
return 0;
}

在我的系统上,tv_nsec 对于除 CLOCK_THREAD_CPUTIME_ID 之外的所有系统都是 1000,对于 CLOCK_THREAD_CPUTIME_ID 的值>tv_nsec1,这意味着其他时钟类型的精度为 1 毫秒(1000 纳秒),而 CLOCK_THREAD_CPUTIME_ID 的精度为 1 纳秒。

对于调用 localtime 的第一个函数该函数的精度为 1 秒,因为该函数以秒为单位计算从 Unix 纪元开始的时间。

What do the compiler options -O0 -lrt mean when I have to compile with gcc -O0 -lrt timing.c -o timing?

对于像gccclang 这样的编译器,选项-O 意味着在将代码编译到指定级别时优化代码,所以-O0 表示根本不优化代码,这在调试代码时通常很有用。

-l 选项表示针对指定的库进行编译,因此 -lrt 表示使用 rt 库进行编译,或者“真正的时间图书馆”;这在某些系统上是必需的,因为可以在该库中定义 CLOCK_REALTIME

希望对您有所帮助。

关于时序测量的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54815428/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com