计算执行函数的时间

时间:2021-10-24 01:21:16

I need to calculate the execution time of a function.

我需要计算一个函数的执行时间。

Currently, I use time.h

目前,我使用time.h

At the beginning of the function:

在功能的开头:

time_t tbegin,tend;
double texec=0.000;
time(&tbegin);

Before the return:

返回前:

 time(&tend);
 texec = difftime(tend,tbegin);

It works fine but give me a result in texec as a integer.

它工作正常,但作为整数给我一个texec的结果。

How can I have my execution time in milliseconds ?

如何以毫秒为单位执行时间?

4 个解决方案

#1


Most of the simple programs have computation time in milli-seconds. So, i suppose, you will find this useful.

大多数简单程序的计算时间以毫秒为单位。所以,我想,你会发现这很有用。

    #include <time.h>
    #include <stdio.h>
    int main()
    {
        clock_t start = clock();
           // Execuatable code
        clock_t stop = clock();
        double elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
        printf("Time elapsed in ms: %f", elapsed);
     }

If you want to compute the runtime of the entire program and you are on a Unix system, run your program using the time command like this time ./a.out

如果你想计算整个程序的运行时并且你在Unix系统上,那么使用time命令运行你的程序就像这次./a.out

#2


You can use a lambda with auto parameters in C++14 to time your other functions. You can pass the parameters of the timed function to your lambda. I'd do it like this:

您可以在C ++ 14中使用带有自动参数的lambda来计时其他函数。您可以将定时函数的参数传递给lambda。我这样做:

// Timing in C++14 with auto lambda parameters

#include <iostream>
#include <chrono>

// need C++14 for auto lambda parameters
auto timing = [](auto && F, auto && ... params)
{
    auto start = std::chrono::steady_clock::now();
    std::forward<decltype(F)>(F)
    (std::forward<decltype(params)>(params)...); // execute the function
    return std::chrono::duration_cast<std::chrono::milliseconds>(
               std::chrono::steady_clock::now() - start).count();
};

void f(std::size_t numsteps) // we'll measure how long this function runs
{
    // need volatile, otherwise the compiler optimizes the loop
    for (volatile std::size_t i = 0; i < numsteps; ++i);
}

int main()
{
    auto taken = timing(f, 500'000'000); // measure the time taken to run f()
    std::cout << "Took " << taken << " milliseconds" << std::endl;

    taken = timing(f, 100'000'000); // measure again
    std::cout << "Took " << taken << " milliseconds" << std::endl;
}

The advantage is that you can pass any callable object to the timing lambda. If you cannot use C++14 auto lambda parameters, then you need to write a templated functor instead, to "simulate" the lambda.

优点是您可以将任何可调用对象传递给时间lambda。如果你不能使用C ++ 14 auto lambda参数,那么你需要编写一个模板化仿函数来“模拟”lambda。

But if you want to keep it simple, you can just do:

但如果你想保持简单,你可以这样做:

auto start = std::chrono::steady_clock::now();
your_function_call_here();
auto end = std::chrono::steady_clock::now();
auto taken = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cout << taken << " milliseconds";

If you know you're not going to change the system time during the run, you can use a std::chrono::high_resolution_clock instead, which may be more precise. std::chrono::steady_clock is however un-sensitive to system time changes during the run.

如果您知道在运行期间不打算更改系统时间,则可以使用std :: chrono :: high_resolution_clock,这可能更精确。但是,std :: chrono :: steady_clock对运行期间的系统时间变化不敏感。

#3


You can create a function like this source:

您可以创建类似此源的函数:

typedef unsigned long long timestamp_t;

static timestamp_t
timestampinmilliseconf ()
{
  struct timeval now;
  gettimeofday (&now, NULL);
  return  now.tv_usec + (timestamp_t)now.tv_sec * 1000000;
}

Then you can use this to get the time difference.

然后你可以用它来获得时差。

timestamp_t time1 = get_timestamp();
// Your function
timestamp_t time2 = get_timestamp();

For windows you can use this function:

对于Windows,您可以使用此功能:

#ifdef WIN32
#include <Windows.h>
#else
#include <sys/time.h>
#include <ctime>
#endif

typedef long long int64; typedef unsigned long long uint64;

/* Returns the amount of milliseconds elapsed since the UNIX epoch. Works on both
 * windows and linux. */

int64 GetTimeMs64()
{
#ifdef WIN32
 /* Windows */
 FILETIME ft;
 LARGE_INTEGER li;

 /* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it
  * to a LARGE_INTEGER structure. */
 GetSystemTimeAsFileTime(&ft);
 li.LowPart = ft.dwLowDateTime;
 li.HighPart = ft.dwHighDateTime;

 uint64 ret = li.QuadPart;
 ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */
 ret /= 10000; /* From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals */

 return ret;
#else
 /* Linux */
 struct timeval tv;

 gettimeofday(&tv, NULL);

 uint64 ret = tv.tv_usec;
 /* Convert from micro seconds (10^-6) to milliseconds (10^-3) */
 ret /= 1000;

 /* Adds the seconds (10^0) after converting them to milliseconds (10^-3) */
 ret += (tv.tv_sec * 1000);

 return ret;
#endif
}

Source

#4


in the header <chrono> there is a class std::chrono::high_resolution_clock
that does what you want. it's a bit involved to use though;

在标题 中有一个类std :: chrono :: high_resolution_clock可以满足您的需求。虽然使用它有点涉及;

#include <chrono>
using namespace std;
using namespace chrono;

auto t1 = high_resolution_clock::now();
// do calculation here
auto t2 = high_resolution_clock::now();
auto diff = duration_cast<duration<double>>(t2 - t1); 
// now elapsed time, in seconds, as a double can be found in diff.count()
long ms = (long)(1000*diff.count());

#1


Most of the simple programs have computation time in milli-seconds. So, i suppose, you will find this useful.

大多数简单程序的计算时间以毫秒为单位。所以,我想,你会发现这很有用。

    #include <time.h>
    #include <stdio.h>
    int main()
    {
        clock_t start = clock();
           // Execuatable code
        clock_t stop = clock();
        double elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
        printf("Time elapsed in ms: %f", elapsed);
     }

If you want to compute the runtime of the entire program and you are on a Unix system, run your program using the time command like this time ./a.out

如果你想计算整个程序的运行时并且你在Unix系统上,那么使用time命令运行你的程序就像这次./a.out

#2


You can use a lambda with auto parameters in C++14 to time your other functions. You can pass the parameters of the timed function to your lambda. I'd do it like this:

您可以在C ++ 14中使用带有自动参数的lambda来计时其他函数。您可以将定时函数的参数传递给lambda。我这样做:

// Timing in C++14 with auto lambda parameters

#include <iostream>
#include <chrono>

// need C++14 for auto lambda parameters
auto timing = [](auto && F, auto && ... params)
{
    auto start = std::chrono::steady_clock::now();
    std::forward<decltype(F)>(F)
    (std::forward<decltype(params)>(params)...); // execute the function
    return std::chrono::duration_cast<std::chrono::milliseconds>(
               std::chrono::steady_clock::now() - start).count();
};

void f(std::size_t numsteps) // we'll measure how long this function runs
{
    // need volatile, otherwise the compiler optimizes the loop
    for (volatile std::size_t i = 0; i < numsteps; ++i);
}

int main()
{
    auto taken = timing(f, 500'000'000); // measure the time taken to run f()
    std::cout << "Took " << taken << " milliseconds" << std::endl;

    taken = timing(f, 100'000'000); // measure again
    std::cout << "Took " << taken << " milliseconds" << std::endl;
}

The advantage is that you can pass any callable object to the timing lambda. If you cannot use C++14 auto lambda parameters, then you need to write a templated functor instead, to "simulate" the lambda.

优点是您可以将任何可调用对象传递给时间lambda。如果你不能使用C ++ 14 auto lambda参数,那么你需要编写一个模板化仿函数来“模拟”lambda。

But if you want to keep it simple, you can just do:

但如果你想保持简单,你可以这样做:

auto start = std::chrono::steady_clock::now();
your_function_call_here();
auto end = std::chrono::steady_clock::now();
auto taken = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cout << taken << " milliseconds";

If you know you're not going to change the system time during the run, you can use a std::chrono::high_resolution_clock instead, which may be more precise. std::chrono::steady_clock is however un-sensitive to system time changes during the run.

如果您知道在运行期间不打算更改系统时间,则可以使用std :: chrono :: high_resolution_clock,这可能更精确。但是,std :: chrono :: steady_clock对运行期间的系统时间变化不敏感。

#3


You can create a function like this source:

您可以创建类似此源的函数:

typedef unsigned long long timestamp_t;

static timestamp_t
timestampinmilliseconf ()
{
  struct timeval now;
  gettimeofday (&now, NULL);
  return  now.tv_usec + (timestamp_t)now.tv_sec * 1000000;
}

Then you can use this to get the time difference.

然后你可以用它来获得时差。

timestamp_t time1 = get_timestamp();
// Your function
timestamp_t time2 = get_timestamp();

For windows you can use this function:

对于Windows,您可以使用此功能:

#ifdef WIN32
#include <Windows.h>
#else
#include <sys/time.h>
#include <ctime>
#endif

typedef long long int64; typedef unsigned long long uint64;

/* Returns the amount of milliseconds elapsed since the UNIX epoch. Works on both
 * windows and linux. */

int64 GetTimeMs64()
{
#ifdef WIN32
 /* Windows */
 FILETIME ft;
 LARGE_INTEGER li;

 /* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it
  * to a LARGE_INTEGER structure. */
 GetSystemTimeAsFileTime(&ft);
 li.LowPart = ft.dwLowDateTime;
 li.HighPart = ft.dwHighDateTime;

 uint64 ret = li.QuadPart;
 ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */
 ret /= 10000; /* From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals */

 return ret;
#else
 /* Linux */
 struct timeval tv;

 gettimeofday(&tv, NULL);

 uint64 ret = tv.tv_usec;
 /* Convert from micro seconds (10^-6) to milliseconds (10^-3) */
 ret /= 1000;

 /* Adds the seconds (10^0) after converting them to milliseconds (10^-3) */
 ret += (tv.tv_sec * 1000);

 return ret;
#endif
}

Source

#4


in the header <chrono> there is a class std::chrono::high_resolution_clock
that does what you want. it's a bit involved to use though;

在标题 中有一个类std :: chrono :: high_resolution_clock可以满足您的需求。虽然使用它有点涉及;

#include <chrono>
using namespace std;
using namespace chrono;

auto t1 = high_resolution_clock::now();
// do calculation here
auto t2 = high_resolution_clock::now();
auto diff = duration_cast<duration<double>>(t2 - t1); 
// now elapsed time, in seconds, as a double can be found in diff.count()
long ms = (long)(1000*diff.count());