2014-07-13 2 views
-1

코드를 실행하여 행렬 곱셈 코드에 걸린 시간을 계산합니다.스레드가 걸리는 시간이 프로세스에 걸린 총 시간보다 긴 이유는 무엇입니까?

나는 네 개의 스레드를 생성하고이 같은 계산 방법 불렀다 :이 내가 행렬 곱셈

void calculate() 
{ 
clock_t starttime = clock(); 
// some Code 
clock_t endtime = clock(); 
cout << "Time Taken:"<<diffclock(endtime, starttime)<<"sec."<<endl; 
} 

를하고있는 중이 코드는이에 대한 방법입니다

std::thread t1(Calculate); 
std::thread t2(Calculate); 
std::thread t3(Calculate); 
std::thread t4(Calculate); 
t1.join(); 
t2.join(); 
t3.join(); 
t4.join(); 

입니다 시차를 계산하십시오 :

double diffclock(clock_t clock1,clock_t clock2) 
{ 
double diffticks=clock1-clock2; 
double diffms=(diffticks)/CLOCKS_PER_SEC; 
return diffms; 
} 

실행 후 전체 실행 시간이 잘못 표시됩니다. 작업에 소요 된 시간은 약 22 초이지만 코드는 소요되는 시간이 거의 32 초입니다. 나는 스톱워치에서 그것을 체크하고이 코드에 의한 결과는 틀렸다.

In order to measure the time spent in a program, clock() should be called 
at the start of the program and its return value subtracted from the value 
returned by subsequent calls. The value returned by clock() is defined for 
compatibility across systems that have clocks with different resolutions. 
To determine the time in seconds, the value returned by clock() should be 
divided by the value of the macro CLOCKS_PER_SEC. CLOCKS_PER_SEC is defined 
to be one million in <time.h>. 

코드를 산출이 시간에 의해 반환되는 시간은 IDE에 의해 제공되는 시간과 모순 그러나 clock의 문서로서 당

This is the screen-shot of console output

. 나는 여기에 code :: blocks을 사용하고있다.

실종 됐나요? 당신이 C++ (11)에있어 이후

+0

'clock()'은 시간을 측정하지 않고 CPU 사이클 만 측정합니까? – marekful

+0

@ MarcellFülöp 그래서 문제는 clock()에 있습니다. 문서를 확인하게되면 곧 당신에게 보내질 것입니다. –

+0

@ MarcellFülöp이 풀 그림을 보라. http://pubs.opengroup.org/onlinepubs/7908799/xsh/clock.html –

답변

1

, 당신은 std::chrono을 사용할 수 있습니다 : cout을 액세스 할 때 또한 std::mutex를 사용해야합니다

std::chrono::time_point<std::chrono :: system_clock> start, end; 
start = std::chrono::system_clock::now(); 
// calculations here... 
end = std::chrono::system_clock::now(); 
std::chrono::duration<double> elapsed = end-start; 
std::cout << "Elapsed time: " << elapsed.count() << "s\n"; 

참고. 귀하의 코드는 괜찮아 보이지만, 법정은 아마 섞여지고있다.

+0

감사합니다. 작동하는지 확인하겠습니다. –

+0

''cout << ''에 오류가 있습니다. 경과 시간 : "<< elapsed.count <<"s \ n;''오류 : 종료 문자가 없습니다 ' –

+0

마지막 줄에 문제가 있습니다. .cout << "경과 시간 :"<< elapsed.count() << endl;'감사합니다. –