sleep.c

来自「Algorithms for Image Processing and Comp」· C语言 代码 · 共 52 行

C
52
字号
/*
 * Copyright (C) 1993 Chris Boucher, ccb@soton.ac.uk.
 *
 * This software may be used freely so long as this copyright notice is
 * left intact. There is no warranty on the software.
 */

#include <stdlib.h>
#include <sys/time.h>

static void etime(struct timeval a, struct timeval b, struct timeval *r)
{
	r->tv_sec = b.tv_sec - a.tv_sec;
	r->tv_usec = b.tv_usec - a.tv_usec;

	if (r->tv_usec < 0) {
		long t = 1 - (r->tv_usec / 1000000);
		r->tv_sec -= t;
		r->tv_usec += t * 1000000;
	}

}


unsigned
sleep(unsigned int seconds)
{
	struct timeval a, b, r;

	gettimeofday(&a, NULL);
	while (1) {
		gettimeofday(&b, NULL);
		etime(a, b, &r);
		if (r.tv_sec >= (long)seconds)
			return 0;
	}
}

unsigned
usleep(unsigned int useconds)
{
	struct timeval a, b, r;

	gettimeofday(&a, NULL);
	while (1) {
		gettimeofday(&b, NULL);
		etime(a, b, &r);
		if (((r.tv_sec * 1000000) + r.tv_usec) >= (long)useconds)
			return 0;
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?