简体   繁体   中英

How can I time my C program?

I looked through old threads but could not find the answer to my question:

How can I time the body of my function inside a C program?

A simple method is to use the 'clock' function:

#include <time.h>

clock_t start, end;
double cpu_time_used;

start = clock();
... /* Do whatever you want to time */
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

Or if you're on linux you can use the 'time' command to time how long it takes your app to execute; this doesn't allow you to time a specific code section though, and includes time taken to initiate the process etc.

time ./myapp

Edit: This is very much a basic 'hack-in-a-quick-timer' approach. For true performance profiling you want to look at a proper profiler, as suggested by Larry Watanabe.

It depends on your compiler and OS. On Sun workstations, I used to use "prof" or "gprof". There is surely a profiling tool for your compiler, OS, and machine - just google "C profile yourOS yourcompiler" (substitute the name of your OS and your compiler )

The basic method is using the clock() function, that is where we all started.

Ex.:


clock_t start = clock();
/* Your code */
printf("Time elapsed: %f\n", ((double)clock() - start) / CLOCKS_PER_SEC);

However, when you start learning about Operating systems, hardware, schedulers, multi-threading, etc. You realized that execution time is something very subjective. When you want to measure performance (which does not necessarily mean execution time) then you need more robust tools.

Gprof is a really easy to use C profiler, which could help you understand better the concept of performance.

time ./a.out

run above one, and output will be:

real    0m0.017s
user    0m0.017s
sys 0m0.000s

real : Total end to end time taken by program/command

user : Time taken in user mode.

sys : Time taken in kernel mode

不确定C中的特定函数名称,但通常的做法是在正文开始之前存储一个微秒时间戳,然后在结尾处抓取另一个并减去。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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