计算指令执行时间代码

本文通过两个示例介绍了如何使用C语言进行文件读取操作,并分别采用秒级别和毫秒级别的时间测量来评估文件打开及读取的耗时。示例中详细展示了结构体的定义与使用、内存分配、文件指针操作等关键技术点。

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

秒级别的: 

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int main()
{
 time_t cur;
 
 time(&cur);
 printf("opencur1=%d\n",cur);

 FILE *file=fopen("a.txt","r");
 if(file==NULL){printf("file open failed!\n");}

 time(&cur);
 printf("opencur2=%d\n",cur);

 typedef struct{
  int id;
  char name[10];
  double sal;
  }Emp;
 
 Emp*es2=malloc(sizeof(Emp));
 
 time(&cur);
 printf("readcur1=%d\n",cur);

 int n=fread(es2,sizeof(Emp),1,file);
 
 time(&cur);
 printf("readcur2=%d\n",cur);
 fclose(file);
  
 for(int i=0;i<n;i++){
  printf("%d,%s,%g\n",es2[i].id,es2[i].name,es2[i].sal);
 }
 free(es2);
  

}

 

 

毫秒级别的:

#include<stdio.h>
#include<sys/time.h>
#include<stdlib.h>
int main()
{
 struct timeval t_start,t_end;
 long const_timeopen=0;
 long const_timeread=0;
 
 //get opent sart time
 gettimeofday(&t_start,NULL);
 printf("start open time :%ld us\n",t_start.tv_usec);

 FILE *file=fopen("test.info.swp","r");
 if(file==NULL){printf("file open failed!\n");}

 //get end time
 gettimeofday(&t_end,NULL);
 printf("end open time:%ld us\n",t_end.tv_usec);

 //const open time
 const_timeopen=t_end.tv_usec-t_start.tv_usec;
 printf("const open time :%ld us\n",const_timeopen);

 typedef struct{
  int id;
  char name[10];
  double sal;
  }Emp;
 
 Emp*es2=malloc(sizeof(Emp));
 


 //get read sart time
 gettimeofday(&t_start,NULL);
 printf("start read time :%ld us\n",t_start.tv_usec);

 int n=fread(es2,sizeof(Emp),1,file);

 //get end time
 gettimeofday(&t_end,NULL);
 printf("end read time:%ld us\n",t_end.tv_usec);

 //const read time
 const_timeread=t_end.tv_usec-t_start.tv_usec;
 printf("const read time :%ld us\n",const_timeread);
 
 
 fclose(file);
  
 for(int i=0;i<n;i++){
  printf("%d,%s,%g\n",es2[i].id,es2[i].name,es2[i].sal);
 }
 free(es2);
  

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值