Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to use gettimeofday function in Linux to get program execution time

Shulou Source: shulou.com Published: 2022-06-01 21:22:25 10月11日 Update

How to use the gettimeofday function in Linux to get the program execution time? I believe that many inexperienced people are at a loss about this, so this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

The gettimeofday function is usually used to calculate the execution time of a program segment under Linux, and this function is declared in the sys/time.h file. This function receives two structure parameters, timeval and timezone.

The declaration of the two structures is as follows:

Struct timeval {time_t tv_sec; / * seconds * / long tv_usec; / * microseconds * /}; struct timezone {int tz_minuteswest; int tz_dsttime;}

Generally, when the current time is obtained through the gettimeofday function, the second parameter is nullptr. The tv_sec in the structure timeval represents seconds and the tv_usec represents microseconds.

Matlab through tic (start a stopwatch timer) and toc (read the stopwatch timer) two functions to give the running time of the program segment, here through two macro TIC and TOC to achieve. The test code is as follows:

# include # define TIC\ struct timeval time1, time2;\ gettimeofday (& time1, nullptr); # define TOC\ gettimeofday (& time2, nullptr);\ double elapsed_time = (time2.tv_sec-time1.tv_sec) * 1000. +\ (time2.tv_usec-time1.tv_usec) / 1000;\ fprintf (stdout, "Elapsed time:% lf (ms)\ n", elapsed_time); int main () {unsigned int tm {10}; TIC for (int I = 0; I < 1000; + + I) {usleep (tm);} TOC return 0;}

The implementation results are as follows:

Execution process: locate the terminal to the Linux_Code_Test/Samples_cplusplus directory, execute:. / build.sh, then go to the build directory, and execute the generated execution file.

What is Linux system Linux is a free-to-use and free-spread UNIX-like operating system, is a POSIX-based multi-user, multi-task, multi-threaded and multi-CPU operating system, using Linux can run major Unix tools, applications and network protocols.

After reading the above, have you mastered how to use the gettimeofday function in Linux to get the execution time of the program? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Function time program two system structure operating system content parameter file method more directory problem run free helpless for this code task Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple MariaDB macOS MySQL Redmi