본문 바로가기
개발을하자/C++

#Sleep()# 함수 직접 만들어 봅시다!

by _ssu 2015. 6. 2.

 문제 : sleep함수를 작성한다.

 조건 
    1. sleep 함수는 int 형과 char형 두가지 형식을 매개변수로 받는다.
        ex] sleep(1), sleep("1")
     2. 기존 Sleep()함수는 이용하지 않는다.

※ Sleep() 란?
    Sleep은 스레드를 일정시간 정지시키는 함수
    Sleep함수의 원형은 windows.h 헤더파일에 정의 되어있다.
 ex) Sleep(5000); //Sleep 스레드를 5초간 정지시킨다.
       1초 = 1000

■ 생각해보기

조건1을 위해
    atoi()함수 사용 
       atoi() = 문자열을 정수형으로 변환 해주는 함수 
       헤더파일 stdlib.h

조건2를 위해 
     1) 아무 일을 수행하지 않는 반복문 사용
     2) 현재 시간을 반환하는 time()함수 이용
         헤더파일 time.h  
-> 현재 시간에 인자로 받은 시간을 더해 끝날 시간을 확인
   ex) 현재시간이 pm. 10:00:00 인자(기다리는시간)이 2(2초)라면
         끝날시간은 pm. 10:00:02
-> 끝날 시간이 되면 반복문 탈출

 

접기

반복문보기">
while(n_time < w_time)
 {
  n_time = time(NULL); 
 }

접기



접기

#include <iostream>
#include <time.h>
#include <windows.h>
#include <stdlib.h>
using namespace std;

int sleep(char s_time[]);  // 문자열형식
int sleep(int s_time);       // 정수형식

int main()
{
 clock_t start, finish;
 double duration;

 //정수sleep
 start = clock();
 sleep(10);
 finish = clock();
 duration = (double)(finish - start) / CLOCKS_PER_SEC;
 cout <<"정수형식 sleep함수 이용 대기시간 = "<< duration << endl;
 
 //문자sleep
 start = clock();
 sleep("10");
 finish = clock();
 duration = (double)(finish - start) / CLOCKS_PER_SEC;
 cout <<"문자열식 sleep함수 이용 대기시간 = "<< duration << endl;

 return 0;
}

int sleep(int s_time)
{
 /* n_time = 현재시간, w_time = 끝날 시간 */
 time_t n_time=time(NULL), w_time = n_time + s_time;
                                       //끝날 시간 = 현재시간 + 기다려야할 시간

/*
    디버그용
    cout<<"n_time= "<<n_time<<endl;
    cout<<"w_time= "<<w_time<<endl;
*/

 while(n_time < w_time)
 {
     n_time = time(NULL);  //현재 시간 
  }

  return 0;
}

int sleep(char s_time[])
{
 int temp = atoi(s_time);
 /* n_time = 현재시간, w_time = 끝날 시간 */
 time_t n_time= time(NULL), w_time= n_time + temp;
                                         //끝날 시간 = 현재시간 + 기다려야할 시간
 
/*
    디버그용
    cout<<"n_time= "<<n_time<<endl;
    cout<<"w_time= "<<w_time<<endl;
*/

 while(n_time < w_time)
 {
     n_time = time(NULL);  //현재 시간 
  }
 return 0;
}


'개발을하자 > C++' 카테고리의 다른 글

#Hello World!# in C++  (0) 2015.06.02

댓글