c获取程序运行时间(纳米级)

本文详细介绍了使用C语言进行时间测量的方法,包括利用clock_gettime函数获取高精度时间戳,通过对比开始与结束时间来计算代码段的执行时间。示例代码展示了两种不同方式的实现,适用于性能测试和代码优化场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
static unsigned long GetTickCount(){
      struct timespec ts;
      clock_gettime(CLOCK_MONOTONIC, &ts);
      return (ts.tv_sec*1000000 + ts.tv_nsec / 1000);
}

int main(){
      unsigned long t0 = GetTickCount();
    
      // start do your thing
      int i = 0;
      for(i = 0 ; i < 10;i++){
          printf("%d ", i);
      }
      printf("\n");
      //end 
      unsigned long t1 = GetTickCount();
      printf("Cost time:%ld us \n", t1 - t0);
      return 0;
}

或者

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

int main(){
    struct timeval t_start,t_end;
    long cost_time = 0;

    //get start time
    gettimeofday(&t_start, NULL);
    printf("Start time: %ld us", t_start.tv_usec);
    
    //do something
    printf("-------------------\n");

    //get end time
    gettimeofday(&t_end, NULL);
    printf("End time: %ld us\n", t_end.tv_usec);
    
    //calculate time slot
    cost_time = t_end.tv_usec - t_start.tv_usec;
    printf("Cost time: %ld us", cost_time);
    return 0;
}
static uint64_t GetTickCount() {
  struct timespec ts;
  clock_gettime(CLOCK_MONOTONIC, &ts);
  return (ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值