ЮНИХ Си++ измерить время работы участка кода

GAD_FATAL

какая функция выдаёт время?
нужно в мили или нано секундах

Olenenok

clock, см. man clock
но в случае многопоточных программ она работает неверно. поэтому внимательно прочитай мануал, там внизу есть ссылка на другие мануалы, среди них упоминается и функция, которая работает верно во всех случаях

Sebasten

какая функция выдаёт время?
А участок кода принимает как параметр?
Вот так видел делают:

#include <iostream>
#include <ctime>

class CRunTime {
public:
CRunTime(const char* m = "code", std::ostream& os = std::cout) : m_message(m m_pos(&os m_start(clock {}
~CRunTime { *m_pos << "Run time of the " << m_message << " is " << (clock - m_start) / double(CLOCKS_PER_SEC) << " seconds\n";}
private:
const char* m_message;
std::ostream* m_pos;
clock_t m_start;
};
int main(int argc, char* argv[])
{
unsigned long long x;
using namespace std;
CRunTime obj("main");
while (cin >> x)
{
CRunTime _("while");
//sleep(1);
}
return 0;
}

Можно в принципе и с точностью до наносекунд мерять, с бустом только

Olenenok

CRunTime
тупое вендовое название, не богохульствуй больше
я вот никак не могу понять - нахрена вводить "стандарты" названий, всё равно в большинстве случаев нифига не понятно, что это такое, но вот в глазах рябить начинает. а для чтения программы гораздо лучше было бы назвать этот класс fucking_timer - все бы моментально запомнили, чем это фукинг таймер занимается.

Garryss

man 3 clock_gettime
использовать с параметром CLOCK_MONOTONIC

Landstreicher

Может быть не совсем в тему, но я бы посоветовал oprofile (или ему подобные вещи) использовать.

GAD_FATAL

но в случае многопоточных программ она работает неверно.
вот это и интересно, не думал что есть функции , которые работают НЕВЕРНО

Olenenok

неужели сложно догадаться, что это означает буквально, что при запуске в программе потока очень часто по прошествии N секунд clock будет выдавать не N, а N+2 (или N-2) секунды?

GAD_FATAL

man 3 clock_gettimeиспользовать с параметром CLOCK_MONOTONIC
вроде что надо. только мана под рукой нет
какого типа структура и какие выдаёт
можт у кого example есть?

GAD_FATAL

UP!
пока мне не удалось получить от функции вменяемые значения

barbos

NAME
clock_getres, clock_gettime, clock_settime - clock and timer functions (REALTIME)
SYNOPSIS
#include <time.h>
int clock_getres(clockid_t clock_id, struct timespec *res); int clock_gettime(clockid_t clock_id, struct timespec *tp); int clock_settime(clockid_t clock_id, const struct timespec *tp);
DESCRIPTION
The clock_getres function shall return the resolution of any clock. Clock resolutions are implementation-defined and cannot be set by a process. If the argument res is not NULL, the resolution of the specified clock shall be stored in the location pointed to by res. If res is NULL, the clock resolution is not returned. If the time argument of clock_settime is not a multiple of res, then the value is truncated to a multiple of res.
The clock_gettime function shall return the current value tp for the specified clock, clock_id.
The clock_settime function shall set the specified clock, clock_id, to the value specified by tp. Time values that are between two consecutive non-negative integer multiples of the resolution of the specified clock shall be truncated down to the smaller multiple of the resolution.
A clock may be system-wide (that is, visible to all processes) or per-process (measuring time that is meaningful only within a process). All implementations shall support a clock_id of CLOCK_REALTIME as defined in <time.h>. This clock represents the realtime clock for the system. For this clock, the values returned by clock_gettime and specified by clock_settime represent the amount of time (in seconds and nanoseconds) since the Epoch. An implementation may also support additional clocks. The interpretation of time values for these clocks is unspecified.
If the value of the CLOCK_REALTIME clock is set via clock_settime the new value of the clock shall be used to determine the time of expiration for absolute time services based upon the CLOCK_REALTIME clock. This applies to the time at which armed absolute timers expire. If the absolute time requested at the invocation of such a time service is before the new value of the clock, the time service shall expire immediately as if the clock had reached the requested time normally.
Setting the value of the CLOCK_REALTIME clock via clock_settime shall have no effect on threads that are blocked waiting for a relative time service based upon this clock, including the nanosleep function; nor on the expiration of relative timers based upon this clock. Consequently, these time services shall expire when the requested relative interval elapses, independently of the new or old value of the clock.
If the Monotonic Clock option is supported, all implementations shall support a clock_id of CLOCK_MONOTONIC defined in <time.h>. This clock represents the monotonic clock for the system. For this clock, the value returned by clock_gettime represents the amount of time (in seconds and nanoseconds) since an unspecified point in the past (for example, system start-up time, or the Epoch). This point does not change after system start-up time. The value of the CLOCK_MONOTONIC clock cannot be set via clock_settime. This function shall fail if it is invoked with a clock_id argument of CLOCK_MONOTONIC.
The effect of setting a clock via clock_settime on armed per-process timers associated with a clock other than CLOCK_REALTIME is implementation-defined.
If the value of the CLOCK_REALTIME clock is set via clock_settime the new value of the clock shall be used to determine the time at which the system shall awaken a thread blocked on an absolute clock_nanosleep call based upon the CLOCK_REALTIME clock. If the absolute time requested at the invocation of such a time service is before the new value of the clock, the call shall return immediately as if the clock had reached the requested time normally.
Setting the value of the CLOCK_REALTIME clock via clock_settime shall have no effect on any thread that is blocked on a relative clock_nanosleep call. Consequently, the call shall return when the requested relative interval elapses, independently of the new or old value of the clock.
The appropriate privilege to set a particular clock is implementation-defined.
If _POSIX_CPUTIME is defined, implementations shall support clock ID values obtained by invoking clock_getcpuclockid which represent the CPU-time clock of a given process. Implementations shall also support the special clockid_t value CLOCK_PROCESS_CPUTIME_ID, which represents the CPU-time clock of the calling process when invoking one of the clock_* or timer_* functions. For these clock IDs, the values returned by clock_gettime and specified by clock_settime represent the amount of execution time of the process associated with the clock. Changing the value of a CPU-time clock via clock_settime shall have no effect on the behavior of the sporadic server scheduling policy (see Scheduling Policies ).
If _POSIX_THREAD_CPUTIME is defined, implementations shall support clock ID values obtained by invoking pthread_getcpuclockid which represent the CPU-time clock of a given thread. Implementations shall also support the special clockid_t value CLOCK_THREAD_CPUTIME_ID, which represents the CPU-time clock of the calling thread when invoking one of the clock_* or timer_* functions. For these clock IDs, the values returned by clock_gettime and specified by clock_settime shall represent the amount of execution time of the thread associated with the clock. Changing the value of a CPU-time clock via clock_settime shall have no effect on the behavior of the sporadic server scheduling policy (see Scheduling Policies ).
RETURN VALUE
A return value of 0 shall indicate that the call succeeded. A return value of -1 shall indicate that an error occurred, and errno shall be set to indicate the error.
ERRORS
The clock_getres clock_gettime and clock_settime functions shall fail if:
EINVAL
The clock_id argument does not specify a known clock.
The clock_settime function shall fail if:
EINVAL
The tp argument to clock_settime is outside the range for the given clock ID.
EINVAL
The tp argument specified a nanosecond value less than zero or greater than or equal to 1000 million.
EINVAL
The value of the clock_id argument is CLOCK_MONOTONIC.
The clock_settime function may fail if:
EPERM
The requesting process does not have the appropriate privilege to set the specified clock.
The following sections are informative.
EXAMPLES
None.
APPLICATION USAGE
These functions are part of the Timers option and need not be available on all implementations.
Note that the absolute value of the monotonic clock is meaningless (because its origin is arbitrary and thus there is no need to set it. Furthermore, realtime applications can rely on the fact that the value of this clock is never set and, therefore, that time intervals measured with this clock will not be affected by calls to clock_settime.
RATIONALE
None.
FUTURE DIRECTIONS
None.
SEE ALSO
clock_getcpuclockid , clock_nanosleep ,

erotic

вот это и интересно, не думал что есть функции , которые работают НЕВЕРНО
А что тебя удивляет? Некоторые функции работают "верно" при соблюдении некоторых условий. Например, при условии запрета одновременного вызова функции из разных потоков.

Garryss

 /* returns time since predefined mark in milliseconds */
unsigned long int GetTimeStamp
{
struct timespec tm;

clock_gettime(CLOCK_MONOTONIC, &tm);
return (tm.tv_sec * 1000 + tm.tv_nsec / (unsigned long int) 1000000);
}

Если система долго работает, то следует использовать 64-битный тип.

sergey_m

вроде что надо. только мана под рукой нет
FAQ раздела не прочитано.
Оставить комментарий
Имя или ник:
Комментарий: