Open In App

Time delay in C

Last Updated : 15 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this post, we will see how to give a time delay in C code. Basic idea is to get current clock and add the required delay to that clock, till current clock is less than required clock run an empty loop. Here is implementation with a delay function. 

C
// C function showing how to do time delay
#include <stdio.h>
// To use time library of C
#include <time.h>

void delay(int number_of_seconds)
{
	// Converting time into milli_seconds
	int milli_seconds = 1000 * number_of_seconds;

	// Storing start time
	clock_t start_time = clock();

	// looping till required time is not achieved
	while (clock() < start_time + milli_seconds)
		;
}

// Driver code to test above function
int main()
{
	int i;
	for (i = 0; i < 10; i++) {
		// delay of one second
		delay(1);
		printf("%d seconds have passed\n", i + 1);
	}
	return 0;
}


Output

1 seconds have passed
2 seconds have passed
3 seconds have passed
4 seconds have passed
5 seconds have passed
6 seconds have passed
7 seconds have passed
8 seconds have passed
9 seconds have passed
10 seconds have passed

Note: The delay() function doesn't work in Ubuntu. In Ubuntu, we can achieve delays or pauses in execution, using sleep() function and nanosleep() function.


Similar Reads