Domanda

EDIT: It appears to be functioning now. The code has been updated to show my revisions. Thank you all for your help.

I imagine I'm just stupid, but I'm attempting to use ctime to count CPU ticks through my entire program. I'm writing an encryption algorithm for a school project and I'm trying to include a timer so that I can add noise processes, equalizing the amount of time among different key/plaintext combinations. Here is a little test for ctime:

#include <iostream>
#include <string>
#include <ctime>

int main (int arc, char **argv)
{
  double elapsedTime;
  const clock_t start = clock ();

  int uselessInt = 0;
  for (int i = 0; i <= 200; i++)
    {
      uselessInt = uselessInt * 2 / 3 + i;
      std::cout << uselessInt << std::endl;
    }

  clock_t end = clock();
  elapsedTime = static_cast<double>(end - start);

  std::cout << elapsedTime << " CPU ticks have elapsed since this application's initiation." << std::endl;
  return (0);
}

which prints:

0
1
2
4
/* ... long list of numbers ... */
591
594
0 CPU ticks have elapsed since this application's initiation.
[smalltock@localhost Desktop]$ 

I am using GCC (G++) and it appears that ctime/time.h simply isn't counting ticks like I want it to. Can anybody identify the problem? I'm a relative amateur in this language.

È stato utile?

Soluzione

My two cents. When you do cin.get(), it waits for your to input something on the console, did you do anything or simply typed enter?

I did run your code without typing any text but simply press enter, it gave the following output:

Test Text
It's a stone, Luigi... you didn't make it.
0 CPU ticks have elapsed since this application's initiation.

Real    0m0.700s
User    0m0.000s
Sys     0m0.061s

It may be because the precision of CLOCKS_PER_SEC is kind of "big" (in seconds) compared to the CPU time used by your program

Meanwhile, a syntax error in duration line, you either missed another ) or should delete the first (

BTW: Real is wall clock time - time from start to finish of the call.

User is the amount of CPU time spent in user-mode code (outside the kernel) within the process. This is only actual CPU time used in executing the process.

Sys is the amount of CPU time spent in the kernel within the process.

So you basically have 0 CPU time since you are keep waiting for I/O, no CPU computation.

Altri suggerimenti

elapsedTime in your program is a measure of time in seconds, not a count of clock ticks. If you want ticks, use duration.

Since your program (presumably) spends the vast majority of its time blocked on I/O, not very many seconds are going to have gone by.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top