The delay function in C + +

Source: Internet
Author: User
Tags sleep sleep function

1. Recommended sleep ();

Ms VC + + can use MFC's sleep function, the parameter is milliseconds.

Included in header file <windows.h>

/*#include<iostream>
#include<windows.h>
using namespace std;


void main()
{


Sleep(1000); //延时1秒
cout<<"adsd"<<endl;
Sleep(10000); // 注意S大写
cout<<"123"<<endl;


}   */

2.delay ();

The delay function must be written by itself, not in the compiler.

#include <time.h>
void delay(int sec)
{
time_t start_time, cur_time; // 变量声明
time(&start_time);
do { time(&cur_time);
} while((cur_time - start_time) < sec );
}

And then you can call it directly.

Such as:

#include<iostream.h>
#include <time.h>
void delay(int sec)
{
time_t start_time, cur_time; // 变量声明
time(&start_time);

do {
time(&cur_time);
} while((cur_time - start_time) < sec );
}

void main()
{
cout<<"a"<<endl;
delay(5); // 滞后5秒
cout<<"b"<<endl;
}

Delay, shorter than one second, can be written like this:

clock_t start_time, cur_time;
start_time = clock();
while((clock() - start_time) < 3.0 * CLOCKS_PER_SEC)
{
}

But some compilers do not support clock

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.