What's new

C/C++ Is there any way to time functions without sleep?

  • Thread starter Maybe Ethernet
  • Start date
  • Views 600
Maybe Ethernet

Maybe Ethernet

Emo? :O
Messages
993
Reaction score
225
Points
125
Sin$
0
Title says it all really :/ i dont want it to stop everything just time one while all the other ones are going
 
Maybe Ethernet

Maybe Ethernet

Emo? :O
Messages
993
Reaction score
225
Points
125
Sin$
0
It would help if you showed us the code you're working with.
like for eg:

void Test(int i){
printf("Im");
Timer Here;//i dont want the timer to pause the application like sleep does.
printf("Awesome");
}
 
P

pwfdc

Member
Bright Idea Programmer Experienced Veteran
Messages
1,540
Reaction score
677
Points
465
Sin$
0
like for eg:

void Test(int i){
printf("Im");
Timer Here;//i dont want the timer to pause the application like sleep does.
printf("Awesome");
}
Well. I have a snippet of code that I wrote in C#. Here it is. It was for a simple splash screen. I did this like a year ago, so it's not the best for a splash screen. However, the concept still will work for you.

Code:
        Timer t;
        private void splashScreen_Shown(object sender, EventArgs e)
        {
            t = new Timer();
            t.Interval = 2000;
            t.Start();
            t.Tick += new EventHandler(t_Tick);
        }
        void t_Tick(object sender, EventArgs e)
        {
            t.Stop();
            Main_Window p = new Main_Window();
            p.Show();
            this.Hide();
        }

If you need an explanation of anything. Let me know.
 
Maybe Ethernet

Maybe Ethernet

Emo? :O
Messages
993
Reaction score
225
Points
125
Sin$
0
Well. I have a snippet of code that I wrote in C#. Here it is. It was for a simple splash screen. I did this like a year ago, so it's not the best for a splash screen. However, the concept still will work for you.

Code:
        Timer t;
        private void splashScreen_Shown(object sender, EventArgs e)
        {
            t = new Timer();
            t.Interval = 2000;
            t.Start();
            t.Tick += new EventHandler(t_Tick);
        }
        void t_Tick(object sender, EventArgs e)
        {
            t.Stop();
            Main_Window p = new Main_Window();
            p.Show();
            this.Hide();
        }

If you need an explanation of anything. Let me know.
do you have skype? cause i need an explanation
 
P

pwfdc

Member
Bright Idea Programmer Experienced Veteran
Messages
1,540
Reaction score
677
Points
465
Sin$
0
Okay Maybe Ethernet Maybe Ethernet , I'll explain it more or less. We'll step through it. Remember though, this is in C# and I will comment it like C#
Code:
Timer t; // Defines the Timer variable which we will use later. 
private void splashScreen_Shown(object sender, EventArgs e) // This was for my form. It will start this function once it is loaded.
{
t = new Timer(); // Creates a new timer
t.Interval = 2000; // Sets how long it will last. In this case, I believe it's 2 seconds unless something is whacked up in my head. 
t.Start(); // Starts the timer. 
t.Tick += new EventHandler(t_Tick); // This tells it what to do when the timer has hit the interval. 
} 
void t_Tick(object sender, EventArgs e) // Function for what to do after it's done. 
{
t.Stop(); // Stops the timer 

// Add the code you want to run here. 

// All this is specific to my form and not needed at all for you I assume. So don't worry about it. 
Main_Window p = new Main_Window();
p.Show();
this.Hide();
}

I hope that helps a bit.
 
Maybe Ethernet

Maybe Ethernet

Emo? :O
Messages
993
Reaction score
225
Points
125
Sin$
0
Okay Maybe Ethernet Maybe Ethernet , I'll explain it more or less. We'll step through it. Remember though, this is in C# and I will comment it like C#
Code:
Timer t; // Defines the Timer variable which we will use later.
private void splashScreen_Shown(object sender, EventArgs e) // This was for my form. It will start this function once it is loaded.
{
t = new Timer(); // Creates a new timer
t.Interval = 2000; // Sets how long it will last. In this case, I believe it's 2 seconds unless something is whacked up in my head.
t.Start(); // Starts the timer.
t.Tick += new EventHandler(t_Tick); // This tells it what to do when the timer has hit the interval.
}
void t_Tick(object sender, EventArgs e) // Function for what to do after it's done.
{
t.Stop(); // Stops the timer

// Add the code you want to run here.

// All this is specific to my form and not needed at all for you I assume. So don't worry about it.
Main_Window p = new Main_Window();
p.Show();
this.Hide();
}

I hope that helps a bit.
i dont understand this because i dont know c# :frown: i know c++ tho. sorry :/
 
Liquid44

Liquid44

Banned
Programmer
Messages
1,158
Reaction score
691
Points
245
Sin$
0
i dont understand this because i dont know c# :frown: i know c++ tho. sorry :/

If you don't understand that, I'm pretty sure you won't understand a c++ implementation. Anyway heres one way to do it in c++.

You essentially want to create a timer callback system that works on separate threads from the main thread. The c++11 standard has a very nice threading library that does most of the work / hassle of maintaining threads for you.

So create a thread and call your function from there, pass the time as a parameter then call std::this_thread::confused:leep_for(std::chrono::milliseconds(_timeInMS)); Don't forget to synchronize in the main thread when done.
 
Maybe Ethernet

Maybe Ethernet

Emo? :O
Messages
993
Reaction score
225
Points
125
Sin$
0
If you don't understand that, I'm pretty sure you won't understand a c++ implementation. Anyway heres one way to do it in c++.

You essentially want to create a timer callback system that works on separate threads from the main thread. The c++11 standard has a very nice threading library that does most of the work / hassle of maintaining threads for you.

So create a thread and call your function from there, pass the time as a parameter then call std::this_thread::confused:leep_for(std::chrono::milliseconds(_timeInMS)); Don't forget to synchronize in the main thread when done.
you cant pass parameters to a thread only (LPVOID) if your refering to threads like DWORD WINAPI threadnamehere(LPVOID)
 
Liquid44

Liquid44

Banned
Programmer
Messages
1,158
Reaction score
691
Points
245
Sin$
0
you cant pass parameters to a thread only (LPVOID) if your refering to threads like DWORD WINAPI threadnamehere(LPVOID)

I was referring to threading in general, not specific windows API crap. A thread executes a task and that task can be anything...
 
Liquid44

Liquid44

Banned
Programmer
Messages
1,158
Reaction score
691
Points
245
Sin$
0
ohhh ok. nice. so whats the diffrence between the two?

Microsoft likes to do things there own way, I generally avoid windows specific stuff. Last time I checked their c++ compiler didn't fully support c++11 standard.
 
Maybe Ethernet

Maybe Ethernet

Emo? :O
Messages
993
Reaction score
225
Points
125
Sin$
0
Microsoft likes to do things there own way, I generally avoid windows specific stuff. Last time I checked their c++ compiler didn't fully support c++11 standard.
yea cause when i try to do #include <thread> it isent finding it :frown: is there any other way to use threads?
 
AceInfinity

AceInfinity

Enthusiast
Messages
146
Reaction score
39
Points
85
Sin$
0
It's the same syntax.

Same syntax doesn't mean the same libraries and methods necessarily.

Microsoft likes to do things there own way, I generally avoid windows specific stuff. Last time I checked their c++ compiler didn't fully support c++11 standard.

Find one that actually does. It's not as easy as it would seem. GCC doesn't even fully support C++11, and it'll be a while until C++14 is even close to becoming compliant with today's most popular/common compilers. C++ is already a big language, I'm curious to see how much more C++14 adds to the chaos.. Most people don't even know about Clang either. There's nothing wrong with using the Win API though if you don't intend on portability, although in some cases you have to write OS specific implementations anyways and use precompiler directives to determine what should be compiled.

Here's what I use for a quick benchmark:
Code:
#include <iostream>
#include <vector>
#include <cmath>
#include <iterator>
#include <algorithm>

#define _WIN32_WINNT 0X600
#include <ctime>
#include <Windows.h>

// generate primes using an arbitrary search limit
void prime_atkin(const int max_n, std::vector<int> &primes)
{
  std::vector<bool> p(max_n, false);
  int sqrt_limit(static_cast<int>(std::sqrt(max_n)));
  for (int x(1); x <= sqrt_limit; x++)
  {
    const int x2(x * x);
    for (int y(1); y <= sqrt_limit; y++)
    {
      const int y2(y * y);
      int n = (4 * x2) + (y2);
      if (n <= max_n && (n % 12 == 1 || n % 12 == 5))
        p[n] = p[n] ^ true;
      n = (3 * x2) + (y2);
      if (n <= max_n && n % 12 == 7)
        p[n] = p[n] ^ true;
      n = (3 * x2) - (y2);
      if (x > y && n <= max_n && n % 12 == 11)
        p[n] = p[n] ^ true;
    }
  }
  primes.push_back(2);
  primes.push_back(3);
  int a(5);
  for (; a <= sqrt_limit; a += 2)
  {
    if (p[a])
    {
      const int a2(a * a);
      for (int i(a2); i < max_n; i += a2) p[i] = false;
      primes.push_back(a);
    }
  }
  for (; a < max_n; a += 2) if (p[a]) primes.push_back(a);
}

void main_method()
{
  const int max_n = 50;
  std::vector<int> sieve;
  prime_atkin(max_n, sieve);
  std::copy(sieve.begin(), sieve.end() - 1, std::ostream_iterator<int>(std::cout, " + "));
  std::cout << sieve.back();
  std::endl(std::cout);
  int sum = std::accumulate(sieve.begin(), sieve.end(), 0, std::plus<int>());
  std::cout << "Sum [" << sieve.size() << " primes] = " << sum;
}

/* ------------------------------------------------------------------- */
#define DISABLE_BENCHMARK TRUE
#define WARMUP TRUE

#if DISABLE_BENCHMARK
#define AVERAGES 1
#define RUNS 1
#else
#define AVERAGES 10
#define RUNS 100
#endif
int main()
{
#if !DISABLE_BENCHMARK && WARMUP
  for (int i = 0; i < 1000000; ++i) 10 * 10;
#endif
  double total = 0.0;
  for (int i = 0; i < AVERAGES; ++i)
  {
    double run = 0.0;
    for (int j = 0; j < RUNS; ++j)
    {
      clock_t t1(clock());
      main_method();
      clock_t t2(clock());
      run += (double)(t2 - t1) / CLOCKS_PER_SEC;
    }
    total += run / RUNS;
  }
  std::endl(std::cout);
  SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x2B);
  total /= AVERAGES;
  unsigned long ticks = (unsigned long)(total * CLOCKS_PER_SEC);
  std::cout << "Time: " << total << " seconds (approx ~" << total * 1000 << "ms : " << ticks << " ticks)";
  std::cout << "..." << std::endl;
  FlashWindow(GetConsoleWindow(), true);
  getchar();

  return ERROR_SUCCESS;
}
/* ------------------------------------------------------------------- */

Simple example. That console stuff is for visual effects with the Windows console.
 
Last edited:
Top Bottom
Login
Register