Does `clock` measure `sleep` i.e. suspended threads? - c

I am trying to understand the clock_t clock(void); function better and have following question:
Did I understand that correctly that clock measures the number of ticks of a process since it is actively running and sleep suspends the calling thread – in this case there is only one thread, namely the main-thread – and therefore suspends the whole process. Which means that clock does not measure the cpu-time (ticks) of the process, since it is not actively running?
If so what is the recommended way to measure the actual needed time?
"The clock() function returns an approximation of processor time used by the program." Source
"The CPU time (process time) is measured in clock ticks or seconds." Source
"The number of clock ticks per second can be obtained using: sysconf(_SC_CLK_TCK);" Source
#include <stdio.h> // printf
#include <time.h> // clock
#include <unistd.h> // sleep
int main()
{
printf("ticks per second: %zu\n", sysconf(_SC_CLK_TCK));
clock_t ticks_since_process_startup_1 = clock();
sleep(1);
clock_t ticks_since_process_startup_2 = clock();
printf("ticks_probe_1: %zu\n", ticks_since_process_startup_1);
printf("sleep(1);\n");
printf("ticks_probe_2: %zu\n", ticks_since_process_startup_2);
printf("ticks diff: %zu <-- should be 100\n", ticks_since_process_startup_2 - ticks_since_process_startup_1);
printf("ticks diff sec: %Lf <-- should be 1 second\n", (long double)(ticks_since_process_startup_2 - ticks_since_process_startup_1) / CLOCKS_PER_SEC);
return 0;
}
Resulting Output:
ticks per second: 100
ticks_probe_1: 603
sleep(1);
ticks_probe_2: 616
ticks diff: 13 <-- should be 100
ticks diff sec: 0.000013 <-- should be 1 second

Does clock measure sleep i.e. suspended threads?
No.
(Well, it could measure it, there's nothing against it. You could have a very bad OS that implements sleep() as a while (!time_to_sleep_expired()) {} busy loop. But any self-respected OS will try to make the process not to use CPU when in sleep()).
Which means that clock does not measure the cpu-time (ticks) of the process, since it is not actively running?
Yes.
If so what is the recommended way to measure the actual needed time?
To measure "real-time" use clock_gettime(CLOCK_MONOTONIC, ...) on a POSIX system.
The number of clock ticks per second can be obtained using: sysconf(_SC_CLK_TCK);
Yes, but note that sysconf(_SC_CLK_TCK); is not CLOCKS_PER_SECOND. You do not use ex times() in your function, you use clock(), I do not really get why you print sysconf(_SC_CLK_TCK);. Anyway, see for example sysconf(_SC_CLK_TCK) vs. CLOCKS_PER_SEC .

Related

How to get execution time of c program?

I am using clock function for my c program to print execution time of current program.I am getting wrong time in output.I want to display time in seconds,milliseconds and microseconds.
#include <stdio.h>
#include <unistd.h>
#include <time.h>
int main()
{
clock_t start = clock();
sleep(3);
clock_t end = clock();
double time_taken = (double)(end - start)/CLOCKS_PER_SEC; // in seconds
printf("time program took %f seconds to execute \n", time_taken);
return 0;
}
time ./time
time program took 0.081000 seconds to execute
real 0m3.002s
user 0m0.000s
sys 0m0.002s
I expect output around 3 seconds however it display wrong.
As you see if I run this program using Linux command time I am getting correct time,I want to display same time using my c program.
Contrary to popular belief, the clock() function retrieves CPU time, not elapsed clock time as the name confusingly may induce people to believe.
Here is the language from the C Standard:
7.27.2.1 The clock function
Synopsis
#include <time.h>
clock_t clock(void);
Description
The clock function determines the processor time used.
Returns
The clock function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation. To determine the time in seconds, the value returned by the clock function should be divided by the value of the macro CLOCKS_PER_SEC. If the processor time used is not available, the function returns the value (clock_t)(−1). If the value cannot be represented, the function returns an unspecified value.
To retrieve the elapsed time, you should use one of the following:
the time() function with a resolution of 1 second
the timespec_get() function which may be more precise, but might not be available on all systems
the gettimeofday() system call available on linux systems
the clock_gettime() function.
See What specifically are wall-clock-time, user-cpu-time, and system-cpu-time in UNIX? for more information on this subject.
Here is a modified version using gettimeoday():
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
int main() {
struct timeval start, end;
gettimeofday(&start, NULL);
sleep(3);
gettimeofday(&end, NULL);
double time_taken = end.tv_sec + end.tv_usec / 1e6 -
start.tv_sec - start.tv_usec / 1e6; // in seconds
printf("time program took %f seconds to execute\n", time_taken);
return 0;
}
Output:
time program took 3.005133 seconds to execute

Array sum with 4 threads is slower than 1 thread [duplicate]

I've always used clock() to measure how much time my application took from start to finish, as;
int main(int argc, char *argv[]) {
const clock_t START = clock();
// ...
const double T_ELAPSED = (double)(clock() - START) / CLOCKS_PER_SEC;
}
Since I've started using POSIX threads this seem to fail. It looks like clock() increases N times faster with N threads. As I don't know how many threads are going to be running simultaneously, this approach fails. So how can I measure how much time has passed ?
clock() measure the CPU time used by your process, not the wall-clock time. When you have multiple threads running simultaneously, you can obviously burn through CPU time much faster.
If you want to know the wall-clock execution time, you need to use an appropriate function. The only one in ANSI C is time(), which typically only has 1 second resolution.
However, as you've said you're using POSIX, that means you can use clock_gettime(), defined in time.h. The CLOCK_MONOTONIC clock in particular is the best to use for this:
struct timespec start, finish;
double elapsed;
clock_gettime(CLOCK_MONOTONIC, &start);
/* ... */
clock_gettime(CLOCK_MONOTONIC, &finish);
elapsed = (finish.tv_sec - start.tv_sec);
elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
(Note that I have done the calculation of elapsed carefully to ensure that precision is not lost when timing very short intervals).
If your OS doesn't provide CLOCK_MONOTONIC (which you can check at runtime with sysconf(_SC_MONOTONIC_CLOCK)), then you can use CLOCK_REALTIME as a fallback - but note that the latter has the disadvantage that it will generate incorrect results if the system time is changed while your process is running.
What timing resolution do you need? You could use time() from time.h for second resolution. If you need higher resolution, then you could use something more system specific. See Timer function to provide time in nano seconds using C++

Is the CLOCKS_PER_SEC value "wrong" inside a virtual machine

I code inside a virtual machine( Linux Ubuntu) that's installed on a windows.
According to this page, the CLOCKS_PER_SEC value in the library on Linux should always be 1 000 000.
When I run this code:
int main()
{
printf("%d\n", CLOCKS_PER_SEC);
while (1)
printf("%f, %f \n\n", (double)clock(), (double)clock()/CLOCKS_PER_SEC);
return 0;
}
The first value is 1 000 000 as it should be, however, the value that should show the number of seconds does NOT increase at the normal pace (it takes between 4 and 5 seconds to increase by 1)
Is this due to my working on a virtual machine? How can I solve this?
This is expected.
The clock() function does not return the wall time (the time that real clocks on the wall display). It returns the amount of CPU time used by your program. If your program is not consuming every possible scheduler slice, then it will increase slower than wall time, if your program consumes slices on multiple cores at the same time it can increase faster.
So if you call clock(), and then sleep(5), and then call clock() again, you'll find that clock() has barely increased at all. Even though sleep(5) waits for 5 real seconds, it doesn't consume any CPU, and CPU usage is what clock() measures.
If you want to measure wall clock time you will want clock_gettime() (or the older version gettimeofday()). You can use CLOCK_REALTIME if you want to know the civil time (e.g. "it's 3:36 PM") or CLOCK_MONOTONIC if you want to measure time intervals. In this case, you probably want CLOCK_MONOTONIC.
#include <stdio.h>
#include <time.h>
int main() {
struct timespec start, now;
clock_gettime(CLOCK_MONOTONIC, &start);
while (1) {
clock_gettime(CLOCK_MONOTONIC, &now);
printf("Elapsed: %f\n",
(now.tv_sec - start.tv_sec) +
1e-9 * (now.tv_nsec - start.tv_nsec));
}
}
The usual proscriptions against using busy-loops apply here.

Sleep C function in CodeBlocks (for Windows) doesn't work properly

I'm trying to do a stopwatch in C ( for Windows ), the code seems to work but the time with the Sleep function doesn't match real time.
Process returned 0 (0x0) execution time : 1.907 s
Press any key to continue.
The problem is that the execution time is around 2 seconds but it should be just 1 sec.. just wondering what I am doing wrong since the Sleep function in Windows accepts milliseconds as parameters it should be working.. here is the code
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
int milliseconds=0;
int seconds=0;
int counter;
for(counter=0;counter<1000;counter++) {
Sleep(1);
milliseconds = milliseconds + 1;
printf("%d\n",milliseconds);
if(milliseconds==1000) {
seconds = seconds + 1;
milliseconds = 0;
printf("seconds: %d",seconds);
}
}
return 0;
}
You are sleeping with a timeout of 1ms. In effect you are giving up your timeslice for your current thread which is by default 15,6ms. But if you have a WPF application running just like Visual Studio it will be set to 1ms. Sleep will return not earlier than you wanted to sleep so you will wait effectively up to to timeslices which add up to 2s sleep time.
If you use a profiler like ETWController you can see the thread waits directly.
There you see that we have 1004 context switch events which did wait on average 1,6ms and not 1ms which you did anticipate. There is a lot more to how the OS scheduler influences how long your sleep takes. The best thing is to measure. See for example SpinWait is dangerous.
When I e.g. close all applications which enforce 1ms system timer I will get
a 6,5s sleep duration!
To check the true wait time I have used your code with a highres timer to print the true wait time:
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <chrono>
int main()
{
int milliseconds = 0;
int seconds = 0;
int counter;
auto start = std::chrono::high_resolution_clock::now();
for (counter = 0; counter<1000; counter++) {
Sleep(1);
milliseconds = milliseconds + 1;
//printf("%d\n", milliseconds);
if (milliseconds == 1000) {
seconds = seconds + 1;
milliseconds = 0;
printf("\nseconds: %d", seconds);
}
}
auto stop = std::chrono::high_resolution_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count();
printf("Duration: %dms", ms);
return 0;
}
Here is the output:
ClockRes v2.0 - View the system clock resolution
Copyright (C) 2009 Mark Russinovich
SysInternals - www.sysinternals.com
Maximum timer interval: 15.625 ms
Minimum timer interval: 0.500 ms
Current timer interval: 1.000 ms
seconds: 1
Duration: 1713ms
ClockRes v2.0 - View the system clock resolution
Copyright (C) 2009 Mark Russinovich
SysInternals - www.sysinternals.com
Maximum timer interval: 15.625 ms
Minimum timer interval: 0.500 ms
Current timer interval: 15.625 ms
seconds: 1
Duration: 6593ms
You cannot use the Sleep function to write a stopwatch. It is not intended for timing anything. All it does is cause a thread to yield the rest of its time slice to other competing threads, allowing them to execute. There is no guarantee about the precise amount of time that your thread will sleep. Its execution may be pre-empted by a higher-priority thread. As per the documentation:
If dwMilliseconds is less than the resolution of the system clock, the thread may sleep for less than the specified length of time. If dwMilliseconds is greater than one tick but less than two, the wait can be anywhere between one and two ticks, and so on.
It goes on to talk about how to increase the accuracy of the sleep interval, but that's not what you want, either. Creating a timer would be more appropriate for your purposes, e.g. using the SetTimer function. Specify a callback function and you will be notified when the time has elapsed. If you needed an extremely accurate timer, you could use a multimedia timer. Tutorials are available here. Probably unnecessary for a simple stopwatch, though.
To obtain time counts and implement your own timing facility, you could call the GetTickCount function. Or use the high-resolution timer APIs for maximum resolution. QueryPerformanceCounter returns the current timestamp, which you divide by the result of QueryPerformanceFrequency.
Requests to the operating system are processed on a best-effort basis, without any response time guarantee. Windows is designed and optimized with performance and throughput in mind for general purpose uses, not for real-time tasks. Your process shares the OS with other processes that also want the attention of the OS. The OS only guarantees that the process suspension will last for at least as long as you requested give or take a clock tick. Plus processing time for looping means that you will get inconsistent results from this code.

Measuring execution time with clock in sec in C not working

I'm trying to measure execution time in C using clock() under linux using the following:
#include <time.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char const* argv[])
{
clock_t begin, end;
begin = clock();
sleep(2);
end = clock();
double spent = ((double)(end-begin)) / CLOCKS_PER_SEC;
printf("%ld %ld, spent: %f\n", begin, end, spent);
return 0;
}
The output is:
1254 1296, spent: 0.000042
The documentation says to divide the clock time by CLOCKS_PER_SEC to get the execution time in sec, but this seems pretty incorrect for a 2sec sleep.
What's the problem?
Sleeping takes almost no execution time. The program just has to schedule its wakeup and then put itself to sleep. While it's asleep, it is not executing. When it's woken up, it doesn't have to do anything at all. That all takes a very tiny fraction of a second.
It doesn't take more execution time to sleep longer. So the fact that there's a 2 second period when the program is not executing has no effect.
clock measures CPU time (in Linux at least). A sleeping process consumes no CPU time.
If you want to measure a time interval as if with a stopwatch, regardless of what your process is doing, use clock_gettime with CLOCK_MONOTONIC.
man clock() has the answer:
The clock() function returns an approximation of processor time used by the program.
Which clearly tells that clock() returns the processor time used by the program, not what you were expecting the total run time of the program which is typically done using gettimeofday.

Resources