简体   繁体   English

计算C中程序的执行时间

[英]Calculate the execution time of program in C

I want to calculate and print the time taken by my C program to execute using ftime() specifically..我想计算并打印我的 C 程序专门使用ftime()执行所花费的time ..

I am seeing the man page for ftime() but I don't understand how to use it!我正在查看ftime()的手册页,但我不明白如何使用它!

As @KamilCuk correctly mentioned, ftime() is deprecated and should be displaced with clock_gettime(), see the man page .正如@KamilCuk 正确提到的,ftime() 已被弃用,应该用clock_gettime() 代替,请参见手册页

This and more examples explained here这个和更多的例子在这里解释

#include <stdio.h>
#include <time.h>      // for clock_t, clock()
#include <unistd.h>    // for sleep()
 
#define BILLION  1000000000.0
 
// main function to find the execution time of a C program
int main()
{
    struct timespec start, end;
 
    clock_gettime(CLOCK_REALTIME, &start);
 
    // do some stuff here
    sleep(3);
 
    clock_gettime(CLOCK_REALTIME, &end);
 
    // time_spent = end - start
    double time_spent = (end.tv_sec - start.tv_sec) +
                        (end.tv_nsec - start.tv_nsec) / BILLION;
 
    printf("Time elpased is %f seconds", time_spent);
 
    return 0;
}
  1. If you're in Linux, just use 'time' command to measure the program execution time:如果您在 Linux 中,只需使用“时间”命令测量程序执行时间:
time ./my_programm
  1. Here some code with clock_gettime()这里有一些带有clock_gettime()的代码
#include <stdio.h> //For printf
#include <time.h>  //For clock_gettime

int main (void)
{  
   //Structs for saving timestamps
   struct timespec mt1, mt2; 
   //Variable for time delta calculating 
   long int tt;      
   
   //Get current time
   clock_gettime (CLOCK_REALTIME, &mt1);

   /* do some stuff here */

   //Get current time again
   clock_gettime (CLOCK_REALTIME, &mt2);

   //Calculate the delta between two timestamps
   tt=1000000000*(mt2.tv_sec - mt1.tv_sec)+(mt2.tv_nsec - mt1.tv_nsec);

   //Print the delta
   printf ("Time spent: %ld nsec / %ld ms\n", tt, tt/1000000);

   return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM