sourcecode

경과시간 측정이 용이

copyscript 2022. 7. 30. 18:15
반응형

경과시간 측정이 용이

time()사용하여 프로그램의 다양한 포인트를 측정하려고 합니다.

이해할 수 없는 것은, 왜 이전과 후의 값이 같은가 하는 것입니다.이 방법이 프로그램을 프로파일링하는 최선의 방법이 아니라는 것을 알고 있습니다. 다만 시간이 얼마나 걸리는지 알고 싶을 뿐입니다.

printf("**MyProgram::before time= %ld\n", time(NULL));

doSomthing();
doSomthingLong();

printf("**MyProgram::after time= %ld\n", time(NULL));

시도했습니다.

struct timeval diff, startTV, endTV;

gettimeofday(&startTV, NULL); 

doSomething();
doSomethingLong();

gettimeofday(&endTV, NULL); 

timersub(&endTV, &startTV, &diff);

printf("**time taken = %ld %ld\n", diff.tv_sec, diff.tv_usec);

하면 수 요?**time taken = 0 26339= 26,339 밀리초 = 26.3 밀리초리초초 츠요시

★★는?**time taken = 4 45025합니다.4와밀 25 밀밀?

//***C++11 Style:***
#include <chrono>

std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << "[µs]" << std::endl;
std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << "[ns]" << std::endl;

0 - 델타

델타 함수를 사용하여 시간 차이를 계산합니다.

auto start = std::chrono::steady_clock::now();
std::cout << "Elapsed(ms)=" << since(start).count() << std::endl;

since는 임의의 시점을 받아들여 임의의 기간을 생성합니다(기본값은 밀리초).뭇매를 맞다

template <
    class result_t   = std::chrono::milliseconds,
    class clock_t    = std::chrono::steady_clock,
    class duration_t = std::chrono::milliseconds
>
auto since(std::chrono::time_point<clock_t, duration_t> const& start)
{
    return std::chrono::duration_cast<result_t>(clock_t::now() - start);
}

Demo

1 - 타이머

으로 한 타이머를 합니다.std::chrono:

Timer clock; // Timer<milliseconds, steady_clock>

clock.tick();
/* code you want to measure */
clock.tock();

cout << "Run time = " << clock.duration().count() << " ms\n";

Demo

Timer는 다음과 같습니다

template <class DT = std::chrono::milliseconds,
          class ClockT = std::chrono::steady_clock>
class Timer
{
    using timep_t = typename ClockT::time_point;
    timep_t _start = ClockT::now(), _end = {};

public:
    void tick() { 
        _end = timep_t{}; 
        _start = ClockT::now(); 
    }
    
    void tock() { _end = ClockT::now(); }
    
    template <class T = DT> 
    auto duration() const { 
        gsl_Expects(_end != timep_t{} && "toc before reporting"); 
        return std::chrono::duration_cast<T>(_end - _start); 
    }
};

Howard Hinnant가 지적한 처럼, 우리는 그 지역에 머무르기 위해chrono하여 평균화 비교와 작업을 여기서는 "" 또는 "비교"를 사용합니다).std::chrono::millisecondsO만 할 는 I/O를 count()또는 지속시간의 틱(여기서는 밀리초 단위).

2 - 계장

모든 콜 가능(함수, 함수 객체, 람다 등)을 벤치마킹에 사용할 수 있습니다.를 들어, '기능이 '고 하면 됩니다.F로는 할 수 arg1,arg2과 같은 결과를낳습니다.

cout << "F runtime=" << measure<>::duration(F, arg1, arg2).count() << "ms";

Demo

measure는 다음과 같습니다

template <class TimeT  = std::chrono::milliseconds
          class ClockT = std::chrono::steady_clock>
struct measure
{
    template<class F, class ...Args>
    static auto duration(F&& func, Args&&... args)
    {
        auto start = ClockT::now();
        std::invoke(std::forward<F>(func), std::forward<Args>(args)...);
        return std::chrono::duration_cast<TimeT>(ClockT::now()-start);
    }
};

1)에서한 바와 같이 w (1)의 w/o를 사용합니다..count()O에 의 기간을 편리합니다.를 들어, 평균 「I/O」는 「I/O」로 되어 있습니다.: : 균 :

auto avg = (measure<>::duration(func) + measure<>::duration(func)) / 2;
std::cout << "Average run time " << avg.count() << " ms\n";

+이것이 전달된 함수 호출의 이유입니다.

+전체 코드는 이쪽에서 확인하실 수 있습니다.

+chrono를 기반으로 벤치마킹 프레임워크를 구축하려는 시도가 여기에 기록되어 있습니다.

+ 데모

#include <ctime>

void f() {
  using namespace std;
  clock_t begin = clock();

  code_to_time();

  clock_t end = clock();
  double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
}

time()함수는 1초 이내까지만 정확하지만 1초 이내에는 "확정"이 있습니다.이것은 너무 단순하긴 하지만 쉽고 휴대하기 쉬운 측정입니다.

struct profiler
{
    std::string name;
    std::chrono::high_resolution_clock::time_point p;
    profiler(std::string const &n) :
        name(n), p(std::chrono::high_resolution_clock::now()) { }
    ~profiler()
    {
        using dura = std::chrono::duration<double>;
        auto d = std::chrono::high_resolution_clock::now() - p;
        std::cout << name << ": "
            << std::chrono::duration_cast<dura>(d).count()
            << std::endl;
    }
};

#define PROFILE_BLOCK(pbn) profiler _pfinstance(pbn)

사용방법은 다음과 같습니다.

{
    PROFILE_BLOCK("Some time");
    // your code or function
}

범위에서는 RAII와 유사합니다.

참고 이건 내 것이 아니지만, 난 이게 여기와 관련이 있다고 생각했어

당신의 질문에서 알 수 있듯이 코드 실행 후 경과시간을 알고 싶은 것 같습니다.2번입니다. 경우에는 '어느 정도'를 사용해 .difftime()뭇매를 맞다이것으로 당신의 문제가 해결되길 바랍니다.

#include <time.h>
#include <stdio.h>

time_t start,end;
time (&start);
.
.
.
<your code>
.
.
.
time (&end);
double dif = difftime (end,start);
printf ("Elasped time is %.2lf seconds.", dif );

time(NULL)1970년 1월 1일 00:00(에폭)부터 경과한 초수를 반환합니다.따라서 두 값의 차이는 처리에 소요된 초수입니다.

int t0 = time(NULL);
doSomthing();
doSomthingLong();
int t1 = time(NULL);

printf ("time = %d secs\n", t1 - t0);

하면 더 수 요.getttimeofday()time()및 마이크로초 단위로 실행됩니다.

#include <ctime>
#include <cstdio>
#include <iostream>
#include <chrono>
#include <sys/time.h>
using namespace std;
using namespace std::chrono;

void f1()
{
  high_resolution_clock::time_point t1 = high_resolution_clock::now();
  high_resolution_clock::time_point t2 = high_resolution_clock::now();
  double dif = duration_cast<nanoseconds>( t2 - t1 ).count();
  printf ("Elasped time is %lf nanoseconds.\n", dif );
}

void f2()
{
  timespec ts1,ts2;
  clock_gettime(CLOCK_REALTIME, &ts1);
  clock_gettime(CLOCK_REALTIME, &ts2);
  double dif = double( ts2.tv_nsec - ts1.tv_nsec );
  printf ("Elasped time is %lf nanoseconds.\n", dif );
}

void f3()
{
  struct timeval t1,t0;
  gettimeofday(&t0, 0);
  gettimeofday(&t1, 0);
  double dif = double( (t1.tv_usec-t0.tv_usec)*1000);
  printf ("Elasped time is %lf nanoseconds.\n", dif );
}
void f4()
{
  high_resolution_clock::time_point t1 , t2;
  double diff = 0;
  t1 = high_resolution_clock::now() ;
  for(int i = 1; i <= 10 ; i++)
  {
    t2 = high_resolution_clock::now() ;
    diff+= duration_cast<nanoseconds>( t2 - t1 ).count();
    t1 = t2;
  }
  printf ("high_resolution_clock:: Elasped time is %lf nanoseconds.\n", diff/10 );
}

void f5()
{
  timespec ts1,ts2;
  double diff = 0;
  clock_gettime(CLOCK_REALTIME, &ts1);
  for(int i = 1; i <= 10 ; i++)
  {
    clock_gettime(CLOCK_REALTIME, &ts2);
    diff+= double( ts2.tv_nsec - ts1.tv_nsec );
    ts1 = ts2;
  }
  printf ("clock_gettime:: Elasped time is %lf nanoseconds.\n", diff/10 );
}

void f6()
{
  struct timeval t1,t2;
  double diff = 0;
  gettimeofday(&t1, 0);
  for(int i = 1; i <= 10 ; i++)
  {
    gettimeofday(&t2, 0);
    diff+= double( (t2.tv_usec-t1.tv_usec)*1000);
    t1 = t2;
  }
  printf ("gettimeofday:: Elasped time is %lf nanoseconds.\n", diff/10 );
}

int main()
{
  //  f1();
  //  f2();
  //  f3();
  f6();
  f4();
  f5();
  return 0;
}

Linux 에서는 clock_gettime()을 선택하는 것이 좋습니다.실시간 라이브러리(-lrt)를 링크해야 합니다.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

#define BILLION  1000000000L;

int main( int argc, char **argv )
  {
    struct timespec start, stop;
    double accum;

    if( clock_gettime( CLOCK_REALTIME, &start) == -1 ) {
      perror( "clock gettime" );
      exit( EXIT_FAILURE );
    }

    system( argv[1] );

    if( clock_gettime( CLOCK_REALTIME, &stop) == -1 ) {
      perror( "clock gettime" );
      exit( EXIT_FAILURE );
    }

    accum = ( stop.tv_sec - start.tv_sec )
          + ( stop.tv_nsec - start.tv_nsec )
            / BILLION;
    printf( "%lf\n", accum );
    return( EXIT_SUCCESS );
  }

Windows만: (이 답변을 게시한 후 Linux 태그가 추가되었습니다.)

GetTickCount()사용하면 시스템 시작 후 경과한 밀리초 수를 얻을 수 있습니다.

long int before = GetTickCount();

// Perform time-consuming operation

long int after = GetTickCount();

다른 사람들이 이미 지적했듯이 C 표준 라이브러리의 time() 함수는 1초 이상의 해상도를 가지고 있지 않습니다.풀 포터블 C 함수는 clock()밖에 없는 것 같습니다만, 이 함수는 월클럭 시간이 아닌 프로세서 시간을 측정합니다.POSIX 플랫폼(Linux 등)에 한정하는 것에 만족하고 있는 경우는 clock_gettime() 함수를 선택하는 것이 좋습니다.

C++11 이후 다양한 컴파일러 및 운영체제 간에 매우 휴대성이 뛰어난 형태로 보다 뛰어난 해상도를 제공하는 타이밍 기능이 제공되고 있습니다.마찬가지로 boost::datetime 라이브러리는 휴대성이 뛰어난 고해상도 타이밍 클래스를 제공합니다.

이러한 기능을 사용할 때의 과제 중 하나는 시스템클럭 조회로 인한 시간 지연입니다.clock_gettime(), boost::datetime 및 std::chrono를 사용해 본 결과, 이 지연은 마이크로초의 문제가 될 가능성이 있습니다.따라서 코드 중 어느 부분의 지속시간을 측정할 때는 이 정도 크기의 측정 오차를 감안하거나 어떤 방법으로든 제로 오류를 수정해야 합니다.이상적으로는 함수에 걸린 시간의 여러 측정값을 수집하고 여러 런에 걸쳐 걸린 평균 또는 최대/최소 시간을 계산하는 것이 좋습니다.

이러한 휴대성 및 통계 수집 문제를 해결하기 위해 Github에서 사용할 수 있는 cxx-rtimers 라이브러리를 개발하고 있습니다.이 라이브러리는 C++ 코드의 타이밍 블록, 제로 에러 계산, 코드에 내장된 여러 타이머로부터의 통계 보고를 위한 단순한 API를 제공하려고 합니다.C++11 컴파일러를 사용하는 경우,#include <rtimers/cxx11.hpp>

void expensiveFunction() {
    static rtimers::cxx11::DefaultTimer timer("expensiveFunc");
    auto scopedStartStop = timer.scopedStart();
    // Do something costly...
}

프로그램 종료 시 다음과 같은 타이밍 통계 요약이 std::cerr에 기록됩니다.

Timer(expensiveFunc): <t> = 6.65289us, std = 3.91685us, 3.842us <= t <= 63.257us (n=731)

여기에는 평균 시간, 표준 한계값, 상한 및 하한, 이 함수가 호출된 횟수가 표시됩니다.

함수를 사용하는 를 사용할 수 .#include <rtimers/posix.hpp> C가 있는 Boost C++ 컴파일러를 할 수 #include <rtimers/boost.hpp>여러 스레드에서 통계 타이밍 정보를 수집할 수 있는 타이머 클래스 버전도 있습니다.시스템 클럭의 연속된2개의 쿼리와 관련된 제로 에러를 추정할 수 있는 방법도 있습니다.

라이브러리 내 개별 기능의 실행 시간을 측정해야 했습니다.모든 함수의 콜을 시간 측정 기능으로 포장할 필요는 없었습니다.콜 스택이 보기 흉하고 깊어지기 때문입니다.또, 예를 들면, 함수가 일찍 종료하거나 예외를 발생시키거나 할 때, 모든 함수의 상단과 하부에 타이머 코드를 붙이고 싶지 않았습니다.결국 저는 시간을 측정하기 위해 자신의 수명을 사용하는 타이머를 만들었습니다.

이 방법으로 문제의 코드 블록의 선두에 있는 이러한 오브젝트(함수 또는 실제 범위) 중 하나를 인스턴스화하고 인스턴스 파괴자가 인스턴스가 범위를 벗어나면 구축 후 경과된 시간을 측정할 수 있습니다.여기서 완전한 예를 찾을 수 있지만 구조는 매우 단순합니다.

template <typename clock_t = std::chrono::steady_clock>
struct scoped_timer {
  using duration_t = typename clock_t::duration;
  const std::function<void(const duration_t&)> callback;
  const std::chrono::time_point<clock_t> start;

  scoped_timer(const std::function<void(const duration_t&)>& finished_callback) :
      callback(finished_callback), start(clock_t::now()) { }
  scoped_timer(std::function<void(const duration_t&)>&& finished_callback) :
      callback(finished_callback), start(clock_t::now()) { }
  ~scoped_timer() { callback(clock_t::now() - start); }
};

구조체가 범위를 벗어나면 제공된 함수로 다시 호출되므로 타이밍 정보를 사용하여 작업을 수행할 수 있습니다(인쇄, 저장 등). 할 에는 더 복잡한 것을 .std::bindstd::placeholders더 많은 인수를 사용하여 함수를 콜백합니다.

다음은 이 기능을 사용하는 간단한 예입니다.

void test(bool should_throw) {
  scoped_timer<> t([](const scoped_timer<>::duration_t& elapsed) {
    auto e = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(elapsed).count();
    std::cout << "took " << e << "ms" << std::endl;
  });

  std::this_thread::sleep_for(std::chrono::seconds(1));

  if (should_throw)
    throw nullptr;

  std::this_thread::sleep_for(std::chrono::seconds(1));
}

좀 더 신중해지고 싶다면new ★★★★★★★★★★★★★★★★★」delete스코핑에 의존하지 않고 타이머를 명시적으로 기동 및 정지할 수 있습니다.

Matlab향!!

tic는 퍼포먼스를 측정하기 위해 스톱워치 타이머를 시작합니다.이 함수는 tic 명령어 실행 시 내부 시간을 기록합니다.toc★★★★★★ 。

#include <iostream>
#include <ctime>
#include <thread>
using namespace std;

clock_t START_TIMER;

clock_t tic()
{
    return START_TIMER = clock();
}

void toc(clock_t start = START_TIMER)
{
    cout
        << "Elapsed time: "
        << (clock() - start) / (double)CLOCKS_PER_SEC << "s"
        << endl;
}

int main()
{
    tic();
    this_thread::sleep_for(2s);
    toc();

    return 0;
}

time(NULL) 함수는 1970년 1월 1일부터 00:00에 경과한 초수를 반환합니다.그리고 그 함수는 프로그램에서 다른 시간에 호출되기 때문에 C++에서는 항상 다른 시간이 됩니다.

두 번째 프로그램에서 인쇄되는 값은 초 및 마이크로초입니다.

0 26339 = 0.026'339 s =   26339 µs
4 45025 = 4.045'025 s = 4045025 µs

time(NULL)함수 호출은 epoc(1970년 1월1일) 이후 경과한 초수를 반환합니다.예를 들어 다음 두 타임스탬프 간의 차이를 파악해야 합니다.

size_t start = time(NULL);
doSomthing();
doSomthingLong();

printf ("**MyProgram::time elapsed= %lds\n", time(NULL) - start);

저는 보통 다음을 사용합니다.

#include <chrono>
#include <type_traits>

using perf_clock = std::conditional<
    std::chrono::high_resolution_clock::is_steady,
    std::chrono::high_resolution_clock,
    std::chrono::steady_clock
>::type;

using floating_seconds = std::chrono::duration<double>;

template<class F, class... Args>
floating_seconds run_test(Func&& func, Args&&... args)
{
   const auto t0 = perf_clock::now();
   std::forward<Func>(func)(std::forward<Args>(args)...);
   return floating_seconds(perf_clock::now() - t0);
} 

이것은 @nikos-athanasiou가 제안한 것과 같습니다.단, 비정상 클럭을 사용하지 않고 부동초수를 지속시간으로 사용하고 있습니다.

#include<time.h> // for clock
#include<math.h> // for fmod
#include<cstdlib> //for system
#include <stdio.h> //for delay

using namespace std;

int main()
{


   clock_t t1,t2;

   t1=clock(); // first time capture

   // Now your time spanning loop or code goes here
   // i am first trying to display time elapsed every time loop runs

   int ddays=0; // d prefix is just to say that this variable will be used for display
   int dhh=0;
   int dmm=0;
   int dss=0;

   int loopcount = 1000 ; // just for demo your loop will be different of course

   for(float count=1;count<loopcount;count++)
   {

     t2=clock(); // we get the time now

     float difference= (((float)t2)-((float)t1)); // gives the time elapsed since t1 in milliseconds

    // now get the time elapsed in seconds

    float seconds = difference/1000; // float value of seconds
    if (seconds<(60*60*24)) // a day is not over
    {
        dss = fmod(seconds,60); // the remainder is seconds to be displayed
        float minutes= seconds/60;  // the total minutes in float
        dmm= fmod(minutes,60);  // the remainder are minutes to be displayed
        float hours= minutes/60; // the total hours in float
        dhh= hours;  // the hours to be displayed
        ddays=0;
    }
    else // we have reached the counting of days
    {
        float days = seconds/(24*60*60);
        ddays = (int)(days);
        float minutes= seconds/60;  // the total minutes in float
        dmm= fmod(minutes,60);  // the rmainder are minutes to be displayed
        float hours= minutes/60; // the total hours in float
        dhh= fmod (hours,24);  // the hours to be displayed

    }

    cout<<"Count Is : "<<count<<"Time Elapsed : "<<ddays<<" Days "<<dhh<<" hrs "<<dmm<<" mins "<<dss<<" secs";


    // the actual working code here,I have just put a delay function
    delay(1000);
    system("cls");

 } // end for loop

}// end of main 

C++: 플랫폼이라는 이 있습니다.:크로노는 크로스 플랫폼이라는 분명한 장점이 있습니다. POSIX POSIX clock_gettime()에 합니다.에서 모든 Linux 스스 on 。std::chrono::xxx_clock::now()이치노

std::chrono::system_clock::now()
std::chrono::steady_clock::now()
std::chrono::high_resolution_clock::now()

, POSIX 만만만 though만clock_gettime(CLOCK_MONOTONIC, &time)와 같아야 한다steady_clock::now()x3배 이상 빨라!

완벽을 기하기 위한 테스트입니다.

#include <stdio.h>
#include <chrono>
#include <ctime>

void print_timediff(const char* prefix, const struct timespec& start, const 
struct timespec& end)
{
    double milliseconds = end.tv_nsec >= start.tv_nsec
                        ? (end.tv_nsec - start.tv_nsec) / 1e6 + (end.tv_sec - start.tv_sec) * 1e3
                        : (start.tv_nsec - end.tv_nsec) / 1e6 + (end.tv_sec - start.tv_sec - 1) * 1e3;
    printf("%s: %lf milliseconds\n", prefix, milliseconds);
}

int main()
{
    int i, n = 1000000;
    struct timespec start, end;

    // Test stopwatch
    clock_gettime(CLOCK_MONOTONIC, &start);
    for (i = 0; i < n; ++i) {
        struct timespec dummy;
        clock_gettime(CLOCK_MONOTONIC, &dummy);
    }
    clock_gettime(CLOCK_MONOTONIC, &end);
    print_timediff("clock_gettime", start, end);

    // Test chrono system_clock
    clock_gettime(CLOCK_MONOTONIC, &start);
    for (i = 0; i < n; ++i)
        auto dummy = std::chrono::system_clock::now();
    clock_gettime(CLOCK_MONOTONIC, &end);
    print_timediff("chrono::system_clock::now", start, end);

    // Test chrono steady_clock
    clock_gettime(CLOCK_MONOTONIC, &start);
    for (i = 0; i < n; ++i)
        auto dummy = std::chrono::steady_clock::now();
    clock_gettime(CLOCK_MONOTONIC, &end);
    print_timediff("chrono::steady_clock::now", start, end);

    // Test chrono high_resolution_clock
    clock_gettime(CLOCK_MONOTONIC, &start);
    for (i = 0; i < n; ++i)
        auto dummy = std::chrono::high_resolution_clock::now();
    clock_gettime(CLOCK_MONOTONIC, &end);
    print_timediff("chrono::high_resolution_clock::now", start, end);

    return 0;
}

gcc7.2 - O3로 컴파일 했을 때의 출력은 다음과 같습니다.

clock_gettime: 24.484926 milliseconds
chrono::system_clock::now: 85.142108 milliseconds
chrono::steady_clock::now: 87.295347 milliseconds
chrono::high_resolution_clock::now: 84.437838 milliseconds
#include <ctime>
#include <functional>

using namespace std;

void f() {
  clock_t begin = clock();

  // ...code to measure time...

  clock_t end = clock();

  function<double(double, double)> convtime = [](clock_t begin, clock_t end)
  {
     return double(end - begin) / CLOCKS_PER_SEC;
  };

  printf("Elapsed time: %.2g sec\n", convtime(begin, end));

}

여기에 기재되어 있는 것과 유사한 예이며, 추가 변환 기능 + 출력만 있습니다.

경과시간을 자동으로 측정하는 클래스를 만들었습니다.이 링크의 코드(c++11)를 확인해 주세요.https://github.com/sonnt174/Common/blob/master/time_measure.h

Time Measure 클래스의 사용 예:

void test_time_measure(std::vector<int> arr) {
  TimeMeasure<chrono::microseconds> time_mea;  // create time measure obj
  std::sort(begin(arr), end(arr));
}

내부적으로 함수는 시스템의 클럭에 액세스하기 때문에 호출할 때마다 다른 값을 반환합니다.일반적으로 기능하지 않는 언어는 함수의 이름이나 인수만으로는 알 수 없는 많은 부작용과 숨겨진 상태가 있을 수 있습니다.

여기서 tv_sec은 경과한 초수를 저장하고 tv_usec은 경과한 마이크로초를 따로 저장합니다.그리고 그것들은 서로의 변환이 아닙니다.따라서 총 경과 시간을 얻으려면 적절한 단위로 변경하고 추가해야 합니다.

struct timeval startTV, endTV;

gettimeofday(&startTV, NULL); 

doSomething();
doSomethingLong();

gettimeofday(&endTV, NULL); 

printf("**time taken in microseconds = %ld\n",
    (endTV.tv_sec * 1e6 + endTV.tv_usec - (startTV.tv_sec * 1e6 + startTV.tv_usec))
    );

doSomething 함수가 타이머의 정밀도보다 더 빠르게 발생하므로 이 두 함수는 동일합니다.시험:

printf ("**MyProgram::before time= %ld\n", time(NULL));

for(i = 0; i < 1000; ++i) {
    doSomthing();
    doSomthingLong();
}

printf ("**MyProgram::after time= %ld\n", time(NULL));

값이 동일한 이유는 긴 절차가 1초 미만으로 오래 걸리지 않기 때문입니다.함수 끝에 긴 루프(int i = 0; i < 100000000; i++)를 추가하여 문제가 발생하는지 확인할 수 있습니다. 그런 다음 여기서부터 시작할 수 있습니다.

위의 내용이 사실로 판명될 경우 시간을 보다 정확하게 측정하기 위해 다른 시스템 함수(Linux에서 작업하는 것으로 알고 있기 때문에 함수명은 도와드릴 수 없습니다)를 찾을 필요가 있습니다.Linux에 GetTickCount()와 유사한 함수가 있을 것입니다.찾기만 하면 됩니다.

OP의 세 가지 질문에 대한 답변입니다.

"이해할 수 없는 은 왜 이전과 이후의 값이 같은가?"

번째 질문과 샘플 코드는time()는 1초의 분해능을 가지고 있기 때문에, 2개의 기능이 1초 이내에 실행되는 것이 답입니다., 2개의 타이머 마크가1초 경계를 넘나들면 (분명히 논리적으로)1초 통지되는 경우가 있습니다.

에서는 '하다'를 사용하고 있습니다.gettimeofday() .

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

번째 질문: " 결과를 어떻게 읽어야 합니까? 26,339나노초 = 26.3밀리초입니까?"

두 번째 답변은 소요 시간이 0초와 26339마이크로초, 즉 0.026339초라는 것입니다.이것은 1초 이내에 실행되는 첫 번째 예를 나타냅니다.

세 번째 질문은 "4초와 25밀리초를 의미하는 것은?"입니다.

세 번째 답변은 소요시간이 4초와 45025마이크로초, 즉 4.045025초입니다.이는 OP가 이전에 타이밍을 맞춘 두 가지 기능에 의해 수행된 작업을 변경했음을 나타냅니다.

언급URL : https://stackoverflow.com/questions/2808398/easily-measure-elapsed-time

반응형