linux 获取系统每秒的tick

linux 获取系统每秒的tick

##下面主要是通过 sysconf(_SC_CLK_TCK) 这个函数来获取内核的计时频率, 通过 (unsigned long) times( NULL) 来获取当前的系统tick计数

很多人会问 sysconf(_SC_CLK_TCK) 的值是一百,这个是在编内核的时候决定的,具体在哪改我也不知道【滑稽】, 但这个频率 只是内核的计时频率,不是它的运行频率

#include <stdio.h>
#include <arpa/inet.h>   //for inet_ntoa , struct sockaddr_in
#include <unistd.h>
#include <sys/ioctl.h>
#include <time.h>
int main(int argc , char *argv[])
{
    int sysHz = 0;
    sysHz = sysconf(_SC_CLK_TCK);
    printf("sysHz = %ld \n", sysHz );
    printf("tick count in ms: %ul\n", (unsigned long) times( NULL));
    sleep(1);
    printf("tick count in ms: %ul\n", (unsigned long) times( NULL));
    sleep(1);
    printf("tick count in ms: %ul\n", (unsigned long) times( NULL));
    sleep(1);
    printf("tick count in ms: %ul\n", (unsigned long) times( NULL));
    sleep(1);
    printf("tick count in ms: %ul\n", (unsigned long) times( NULL));
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Linux中,可以通过sysconf(_SC_CLK_TCK)函数来获取系统tick计数频率。这个频率表示内核的计时频率,而不是运行频率。具体的代码示例如下: #include <stdio.h> #include <unistd.h> #include <sys/times.h> int main() { long sysHz = sysconf(_SC_CLK_TCK); printf("系统tick计数频率为:%ld\n", sysHz); unsigned long tickCount = (unsigned long) times(NULL); printf("当前tick计数为:%ul\n", tickCount); sleep(1); tickCount = (unsigned long) times(NULL); printf("一秒后的tick计数为:%ul\n", tickCount); sleep(1); tickCount = (unsigned long) times(NULL); printf("再过一秒后的tick计数为:%ul\n", tickCount); return 0; } 这段代码会输出系统tick计数频率以及当前的tick计数,然后分别让程序休眠1秒并再次获取tick计数。这样就可以通过比较tick计数的差值来得到时间的流逝。注意,tick计数的单位是时钟滴答数,需要根据tick计数频率转换为实际的时间单位。 另外,在Linux中还可以使用clock_gettime函数来获取系统的时间。CLOCK_MONOTONIC代表系统启动后流逝的时间,而CLOCK_REALTIME代表现实的时间。具体的代码示例如下: #include <stdio.h> #include <time.h> int main() { struct timespec tp; clock_gettime(CLOCK_MONOTONIC, &tp); printf("系统启动后流逝的时间为:%ld秒 %ld纳秒\n", tp.tv_sec, tp.tv_nsec); clock_gettime(CLOCK_REALTIME, &tp); printf("现实的时间为:%ld秒 %ld纳秒\n", tp.tv_sec, tp.tv_nsec); return 0; } 这段代码会输出系统启动后流逝的时间和现实的时间,单位分别是秒和纳秒。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值