c - 对时序测量的困惑
问题描述
我的任务是实现三个不同的函数 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;
}
解决方案
我如何估计这个?您建议使用哪个计时功能?
如果要获取各种计时元素的分辨率(精度),可以使用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
is之外1000
,对于isCLOCK_THREAD_CPUTIME_ID
的值,这意味着其他时钟类型的精度为 1 毫秒(1000 纳秒),而 的精度为 1 纳秒。tv_nsec
1
CLOCK_THREAD_CPUTIME_ID
对于调用localtime
精度的第一个函数,该函数将计算 Unix 纪元的时间(以秒为单位)。
当我必须使用 gcc -O0 -lrt timing.c -o timing 编译时,编译器选项 -O0 -lrt 是什么意思?
对于某些编译器,gcc
和clang
选项-O
意味着在将代码编译到指定级别时优化代码,因此-O0
意味着根本不优化代码,这在调试代码时通常很有用。
该-l
选项表示针对指定的库-lrt
进行编译,因此表示使用该rt
库或“实时库”进行编译;这在某些系统上是必需的,CLOCK_REALTIME
可以在该库中定义。
我希望这能有所帮助。
推荐阅读
- kohana-3 - Kohana 3 - 将模型保存到数据库中,关系为 belongs_to
- asp.net-mvc - ASP MVC Identity 2 让用户成为“用户”角色
- ruby-on-rails - Ruby - LoadError:无法加载此类文件 - ../credentials_go_in_var_lib/credentials
- java - 如何在 Keystore 中找到证书
- javascript - 如何评估 JSON 的键以匹配特定键并提取该键的值?
- julia - JuMP 变量声明:MethodError
- r - 使用 dplyr 将异常值替换为 R 中多层数据的平均值
- spi - Attiny 84 通过 SPI 故障与 RTC 通信
- python - 尝试使用 Python 3 抓取页面的错误请求
- java - Ojdbc7 不包含 oracle.jdbc.driver.OracleTypes.CURSOR