В этом посте будет обсуждаться, как найти время выполнения программы C в средах Windows и Linux.
Существует четыре широко используемых метода определения времени выполнения программы на C:
1. Использование clock() функция
Мы можем использовать clock() функция, предоставляемая <time.h> заголовочный файл для расчета времени ЦП, потребляемого задачей в приложении C. Он возвращает clock_t type, в котором хранится общее количество тактов часов.
Чтобы вычислить общее количество прошедших секунд, нам нужно разделить общее количество прошедших тактов часов на CLOCKS_PER_SEC макрос (также присутствует в <time.h>) как показано ниже:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
#include <stdio.h>
#include <time.h> // for clock_t, clock(), CLOCKS_PER_SEC
#include <unistd.h> // for sleep()
// основная функция для определения времени выполнения программы на C
intmain()
{
// для хранения времени выполнения кода
doubletime_spent=0.0
clock_t begin=clock()
// делаем здесь что-нибудь
sleep(3)
clock_t end=clock()
// рассчитать прошедшее время, найдя разницу (end – begin) и
// деление разницы на CLOCKS_PER_SEC для перевода в секунды
time_spent+=(double)(end–begin)/CLOCKS_PER_SEC
printf(“The elapsed time is %f seconds”,time_spent)
return0
}
|
Словить Выполнить код
Выход (может варьироваться):
The elapsed time is 0.000014 seconds
Обратите внимание, что clock() Функция не возвращает фактическое количество прошедшего времени, а возвращает количество времени, которое потребовалось базовой операционной системе для запуска процесса. Другими словами, фактическое время настенных часов может быть намного больше.
2. Использование time() функция
The <time.h> заголовок также предоставляет time() функция, которая возвращает общее количество секунд, прошедших с начала Эпохи (00:00:00 UTC, 1 января 1970 г.). Он принимает указатель на time_t в качестве аргумента, который обычно передается как NULL и возвращает time_t тип. Если аргумент не NULL, то возвращаемое значение также сохраняется в памяти, на которую указывает аргумент.
Его использование аналогично clock() функцию, как показано ниже:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#include <stdio.h>
#include <time.h> // for time()
#include <unistd.h> // for sleep()
// основная функция для определения времени выполнения программы на C
intmain()
{
time_t begin=time(NULL)
// делаем здесь что-нибудь
sleep(3)
time_t end=time(NULL)
// вычислить прошедшее время, найдя разницу (end – begin)
printf(“The elapsed time is %d seconds”,(end–begin))
return0
}
|
Словить Выполнить код
результат:
The elapsed time is 3 seconds
3. Использование gettimeofday() функция
The gettimeofday() Функция возвращает время настенных часов, прошедшее с начала эпохи, и сохраняет его в timeval структура, выраженная в секундах и микросекундах.
Он определен в <sys/time.h> заголовочный файл и принимает два аргумента — первый аргумент является ссылкой на timeval структура, а второй аргумент — нулевой указатель. timeval структура объявляется следующим образом: <time.h> заголовок:
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
Следующий код демонстрирует использование gettimeofday() путем измерения времени настенных часов:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#include <stdio.h>
#include <sys/time.h> // for gettimeofday()
#include <unistd.h> // for sleep()
// основная функция для определения времени выполнения программы на C
intmain()
{
structtimeval start,end
gettimeofday(&start,NULL)
// делаем здесь что-нибудь
sleep(5)
gettimeofday(&end,NULL)
longseconds=(end.tv_sec–start.tv_sec)
longmicros=((seconds*1000000)+end.tv_usec)–(start.tv_usec)
printf(“The elapsed time is %d seconds and %d microsn”,seconds,micros)
return0
}
|
Словить Выполнить код
Выход (может варьироваться):
The elapsed time is 5 seconds and 5000147 micros
Эта функция поддерживается компиляторами GCC и может не работать в Windows.
4. Использование clock_gettime() функция
Мы также можем использовать clock_gettime() функция, определенная в <time.h> заголовочный файл, который поддерживает точность до наносекунд. Он принимает два аргумента: первый аргумент — это тип часов, а второй аргумент — указатель на timespec структура. timespec структура обеспечивается <time.h> заголовок и объявляется как:
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
Следующий код вычисляет прошедшее время, используя общесистемные часы реального времени, обозначенные как CLOCK_REALTIME, время которого представляет секунды и наносекунды с начала Эпохи.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#include <stdio.h>
#include <time.h> // for clock_t, clock()
#include <unistd.h> // for sleep()
#define BILLION 1000000000.0
// основная функция для определения времени выполнения программы на C
intmain()
{
structtimespec start,end
clock_gettime(CLOCK_REALTIME,&start)
// делаем здесь что-нибудь
sleep(3)
clock_gettime(CLOCK_REALTIME,&end)
// time_spent = конец – начало
doubletime_spent=(end.tv_sec–start.tv_sec)+
(end.tv_nsec–start.tv_nsec)/BILLION
printf(“The elapsed time is %f seconds”,time_spent)
return0
}
|
Словить код
Обратите внимание, что clock_gettime() будет работать только на очень немногих машинах UNIX.
Вот и все, что касается нахождения времени выполнения программы на C.
Связанный пост:
Измерьте прошедшее время программы C++ с помощью библиотеки Chrono
Источник
In this article, we will discuss how to check the execution time of a Python script.
There are many Python modules like time, timeit and datetime module in Python which can store the time at which a particular section of the program is being executed. By manipulating or getting the difference between times of beginning and ending at which a particular section is being executed, we can calculate the time it took to execute the section.
The following methods can be used to compute time difference:
- Python time module provides various time-related functions. This module comes under Python’s standard utility modules. time.time() method of the Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform-dependent.
- Python datetime module defines a function that can be primarily used to get the current time and date. now() function Return the current local date and time, which is defined under the datetime module.
- Pythontimeit module runs your snippet of code n number of times (the default value is, 1000000) so that you get the statistically most relevant measurement of code execution time.
Using the time module check the execution time of Python
Example 1: Measuring time taken for a code segment by recording start and end times
Computing the time using the time module and time.time() function. We have computed the time of the above program, which came out of the order 10^-3. We can check for the time by increasing the number of computations using the same algorithms.
Python3
import time
start = time.time()
a = 0
for i in range(1000):
a += (i**100)
end = time.time()
print("The time of execution of above program is :",
(end-start) * 10**3, "ms")
Output:
The time of execution of above program is : 0.77056884765625 ms
Example 2: Measuring time taken for a code segment by adding up the time required per iteration
Checking times for execution of the program for different numbers of computations. We see a general trend in the increase in time of computation for an increase in the number of execution. However, it may not show any linear trend or fixed increments.
Python3
import time
for j in range(100, 5501, 100):
start = time.time()
a = 0
for i in range(j):
a += (i**100)
end = time.time()
print(f"Iteration: {j}tTime taken: {(end-start)*10**3:.03f}ms")
Output:
Iteration: 100 Time taken: 0.105ms
Iteration: 200 Time taken: 0.191ms
Iteration: 300 Time taken: 0.291ms
Iteration: 400 Time taken: 0.398ms
Iteration: 500 Time taken: 0.504ms
Iteration: 600 Time taken: 0.613ms
Iteration: 700 Time taken: 0.791ms
...
Iteration: 5400 Time taken: 6.504ms
Iteration: 5500 Time taken: 6.630ms
Explanation: Here we have truncated the output for representation purpose. But if we compare the iterations from 100 to 700 they are less than 1ms. But towards the end of the loop, each iteration taking ~7ms. Thus, there is an increase in time taken as the number of iterations have increased. This is generally because, the inner loop iterate more number of time depending on each outer iteration.
Using the DateTime module check the execution time
Using the datetime module in Python and datetime.now() function to record timestamp of start and end instance and finding the difference to get the code execution time.
Python3
from datetime import datetime
start = datetime.now()
a = 0
for i in range(1000):
a += (i**100)
end = datetime.now()
td = (end - start).total_seconds() * 10**3
print(f"The time of execution of above program is : {td:.03f}ms")
Output:
The time of execution of above program is : 0.766ms
Using timeit module check the execution time
This would give us the execution time of any program. This module provides a simple way to find the execution time of small bits of Python code. It provides the timeit() method to do the same. The module function timeit.timeit(stmt, setup, timer, number) accepts four arguments:
- stmt which is the statement you want to measure; it defaults to ‘pass’.
- setup, which is the code that you run before running the stmt; it defaults to ‘pass’. We generally use this to import the required modules for our code.
- timer, which is a timeit.Timer object; usually has a sensible default value, so you don’t have to worry about it.
- The number, which is the number of executions you’d like to run the stmt.
Example 1: Using timeit inside Python code snippet to measure execution time
Python3
import timeit
mysetup = "from math import sqrt"
mycode =
exec_time = timeit.timeit(stmt=mycode,
setup=mysetup,
number=1000000) * 10**3
print(f"The time of execution of above program is : {exec_time:.03f}ms")
Output:
The time of execution of above program is : 71.161ms Подробнее ...