Sponsored Content
Full Discussion: timing your functions
Top Forums Programming timing your functions Post 302094858 by DreamWarrior on Wednesday 1st of November 2006 03:19:27 PM
Old 11-01-2006
To use gettimeofday you can do this:

Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

static float getTimeDiff(struct timeval *s, struct timeval *e);

void main()
{
    struct timeval  sTv, eTv;

    gettimeofday(&sTv, NULL);

    /* do work */

    gettimeofday(&eTv, NULL);

    printf("Time difference is %.2f seconds\n", getTimeDiff(&sTv, &eTv));
}

The getTimeDiff function works on the two timeval structures to compute the seconds elapsed. The source is simple, and as follows:

Code:
static float getTimeDiff(struct timeval *s, struct timeval *e)
{
	struct timeval	diff_tv;
		
	diff_tv.tv_usec = e->tv_usec - s->tv_usec;
	diff_tv.tv_sec = e->tv_sec - s->tv_sec;
		
	if (s->tv_usec > e->tv_usec)
	{
		diff_tv.tv_usec += 1000000;
		diff_tv.tv_sec--;
	}
		
	return (float) diff_tv.tv_sec + ((float) diff_tv.tv_usec / 1000000.0);
}

Furthermore, it should be noted that clock() does *NOT* return values based upon real time, rather it returns CPU time. If you want to know how much REAL TIME something takes then clock() is not the solution. For example:

Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void main()
{
	int	i, j, t;
	
	clock_t	clockSample[3];

	clockSample[0] = clock();
	
	sleep(2);
		
	clockSample[1] = clock();
	
	for (i = 0; i < 1024; i++)
		for (j = 0; j < 1024; j++)
			t = i * i + j;
	
	clockSample[2] = clock();
	
	for (i = 0; i < 3; i++)
	{
		printf("Clock sample %d is %lu\n", i, clockSample[i]);
	}
}

Upon running this code, you'll notice that the first two samples for clock are positioned squarely at 0. The sleep call, which will take around 2 seconds *real* time, has no effect on the second clock sample. Since sleep takes no CPU time, it is not calculated into the real time usage of the application by clock(). Similar behavior will be seen for other non-CPU (blocking) tasks the application incurs, such as waiting in a select call for socket I/O. The third clock sample, however, does incur CPU time as it is a CPU bound loop. Thus, the third sample will reflect the CPU time incurred by the loop. If, however, you had the crazy idea to insert (for example) a usleep in the loop, you would never calculate the additional real time incurred by the usleep.

So, beware that both methods, while equally useful, answer two different questions. clock() tells you CPU time used, the gettimeofday method tells you actual time elapsed.
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

timing a loop in unix.

hi guys.. i have a shell script that loops through a certain directory to see if a file has been created and then prints the file if it exists... the only problem i have now is that sometimes the flat does not get created by the program thats supposed to create it, in this scenario, my loop... (1 Reply)
Discussion started by: wolkott
1 Replies

2. UNIX for Advanced & Expert Users

scp timing out

having problems using scp in that during peak hours it appears to time out. anyone have similar experiences? any thoughts regarding a solution... (1 Reply)
Discussion started by: jph
1 Replies

3. Shell Programming and Scripting

Timing out a SSH

I need to make it so an autmated process which involves ssh, times out if ssh prompts for a password. Most of the time it shouldnt prompt for a password. But if it does i need it to time it out or get a status and stop the ssh and log that the ssh failed and move onto the next server. Is there any... (9 Replies)
Discussion started by: rcunn87
9 Replies

4. AIX

Kshell scripts and timing

Hello everyone, I have a script thats acting funky, what I would like to do is report to a file, how long its taking to get to certain area's, in seconds. For example. -- Start timer -- Run unix command 1 -- Run unix command 2 -- Stop timer -- Report Seconds -- etc etc Is there a way... (3 Replies)
Discussion started by: dbridle
3 Replies

5. Programming

Help with __builtin_prefetch function and it's timing

Hello there, I just needed to know how to get the timing right when using the gcc __builtin_prefetch() function, that is, how many instructions before the actual utilization of the data should I make the prefetch call. I will be measuring the L1 cache hit rate with valgrind's cachegrind,... (3 Replies)
Discussion started by: Tavo
3 Replies

6. Programming

Weird timing results in C

I was running some timings in my code to see which of several functions was the best and I've been getting some odd results. Here's the code I'm using: static double time_loop(int (*foo)(int)) { clock_t start, end; int n = 0, i = 0; start = clock(); for (; i <= MAXN; i++) if... (6 Replies)
Discussion started by: CRGreathouse
6 Replies

7. Shell Programming and Scripting

Timing a script

i have a very big script i have that i'd like to add a timeout to. this script runs on a several remote host. i update this script with timeout clause and then copy it over to all the hosts on which it is currently on. basically, i want the timeout to make the script abort/exit if it's... (1 Reply)
Discussion started by: SkySmart
1 Replies

8. Shell Programming and Scripting

How to execute functions or initiate functions as command line parameters for below requirement?

I have 7 functions those need to be executed as command line inputs, I tried with below code it’s not executing function. If I run the ./script 2 then fun2 should execute , how to initiate that function I tried case and if else also, how to initiate function from command line if then... (8 Replies)
Discussion started by: saku
8 Replies

9. Red Hat

Hardware and system timing are different

-> We have 2 servers server1 and server2 server. ->server1 is master application and server2 is slave application server. ->output of server1 hardware and slave timing: # hwclock --show Thu 05 Jun 2014 05:34:08 PM SGT -0.465666 seconds # date Thu Jun 5 17:34:16 SGT 2014 # cd... (6 Replies)
Discussion started by: manjusharma128
6 Replies

10. Programming

Byte swap timing

I have noticed the difference in byte swap timing between two Ubuntu systems. The bswap_32 used to work just fine on the old system, but on the new one it lags behind home-grown swap. My code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <byteswap.h> #include... (4 Replies)
Discussion started by: migurus
4 Replies
gettimeofday(3C)					   Standard C Library Functions 					  gettimeofday(3C)

NAME
gettimeofday, settimeofday - get or set the date and time SYNOPSIS
#include <sys/time.h> int gettimeofday(struct timeval *tp, void *tzp); int settimeofday(struct timeval *tp, void *tzp); DESCRIPTION
The gettimeofday() function gets and the settimeofday() function sets the system's notion of the current time. The current time is expressed in elapsed seconds and microseconds since 00:00 Universal Coordinated Time, January 1, 1970. The resolution of the system clock is hardware dependent; the time may be updated continuously or in clock ticks. The tp argument points to a timeval structure, which includes the following members: long tv_sec; /* seconds since Jan. 1, 1970 */ long tv_usec; /* and microseconds */ If tp is a null pointer, the current time information is not returned or set. The TZ environment variable holds time zone information. See TIMEZONE(4). The tzp argument to gettimeofday() and settimeofday() is ignored. Only privileged processes can set the time of day. RETURN VALUES
Upon successful completion, 0 is returned. Otherwise, -1 is returned and errno is set to indicate the error. ERRORS
The settimeofday() function will fail if: EINVAL The structure pointed to by tp specifies an invalid time. EPERM The {PRIV_SYS_TIME} privilege was not asserted in the effective set of the calling process. The gettimeofday() function will fail for 32-bit interfaces if: EOVERFLOW The system time has progressed beyond 2038, thus the size of the tv_sec member of the timeval structure pointed to by tp is insufficient to hold the current time in seconds. USAGE
If the tv_usec member of tp is > 500000, settimeofday() rounds the seconds upward. If the time needs to be set with better than one second accuracy, call settimeofday() for the seconds and then adjtime(2) for finer accuracy. ATTRIBUTES
See attributes(5) for descriptions of the following attributes: +-----------------------------+-----------------------------+ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | +-----------------------------+-----------------------------+ |Interface Stability |gettimeofday() is Standard. | +-----------------------------+-----------------------------+ |MT-Level |MT-Safe | +-----------------------------+-----------------------------+ SEE ALSO
adjtime(2), ctime(3C), gethrtime(3C), TIMEZONE(4), attributes(5), privileges(5), standards(5) SunOS 5.11 1 Aug 2003 gettimeofday(3C)
All times are GMT -4. The time now is 08:44 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy