Why is clock() returning 1.84467e+13? - c++

I am trying to time a code I've got in C++. I have an inner and an outer loop that I want to time separately, but at the same time. For some reason when I do this one of the instances returns 1.84467e+13 and always this exact number.
Why is this happening?
Here is a minimum working example that replicates the effect on my machine:
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
long int i, j;
clock_t start, finish, tick, tock;
double a = 0.0;
double adding_time, runtime;
start = clock();
for(i=0; i<10; i++)
{
a=0.0;
tick =clock();
for(j=0; j<10000000; j++)
{
a+=1;
}
tock= clock();
adding_time = (double)(tick - tock)/CLOCKS_PER_SEC;
cout << "Computation time:" << adding_time << endl;
}
finish = clock();
runtime = (double)(finish - start)/CLOCKS_PER_SEC;
cout << "Total computation time:" << runtime << endl;
}

Your clock_t is apparently an unsigned 64-bit type.
You're taking tick - tock, where tock was measured after tick, so if there's any difference between the two at all, it's going to try to produce a negative number--but since it's an unsigned type, that's wrapping around to become something close to the largest number that can be represented in that type.
Obviously, you really want to use tock-tick instead.

let say tic = 2ms and tac is 4ms; so when you do tic-tac(2-4) that will generate a negative number obviously.. even if it given a positive number it wont be the real time. and also, the number it generate (which doesnt appear on my computer) is a big number, so, try to use the manipulator;
#include"iomanip"
cout << fixed << showpoint;
cout << setprecision(2);
it might work..

Related

Measuring running time of program with clock

We are studying the performance of various sorting algorithms and implemented our version of mergesort. We are trying to measure the running time with different input, but when we run the main() program shown below, we are getting different time results.
For example, clock() function output below can show 30 seconds with large input, but when we use the actual timer using our phones, the main program takes about 2 minutes.
What are we missing here? Are we not using the clock() function in a right way? Why is there such a big difference (1.5 minutes)?
Thank you
int n;
cout << "Enter n - lenght of array" << endl;
cin >> n;
vector<int> v(n);
for(int i = 0; i < n; ++i)
{
v[i] = i;
}
auto rng = default_random_engine {};
std::shuffle(std::begin(v), std::end(v), rng);
clock_t begin = clock();
sort(v);
cout << "done";
clock_t end = clock();
cout <<"total time : " << (double)(end-begin) / CLOCKS_PER_SEC<<endl;
return 0;
I ran your code by replacing the sort function with the std::sort, for n=5000000 it showed 11.744s then I moved the line clock_t begin = clock(); before the declaration of vector v and the time was 13.818s
So it seems memory allocation, O(N) initialization and shuffling can take a good amount of time and if you choose a much bigger number for n, depending on the efficiency of your sort function for a random inputset, initialization can take more time than the sort.

C++ 2 dice rolling 10 million times BEGINNER

I am trying to create a program that will roll 2 dice 10 million times, and output how many times each number is rolled. Along with this, I am tasked with creating a histogram (*=2000) for the outputs.
Here is what I have so far.
/*
Creating a program that counts outcomes of two dice rolls, then show a
histogram of the outcomes.
Section 1 : Simulate ten million times rolls of two dice, while counting
outcomes. (Hint: Use an array of size 13.)
Section 2 : Show the outcome, the numbers of outcomes, and the histogram
(one * designates 20000). Your output must align properly.
*/
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int main()
{
int i, j, ary[13] = {};
cout << "Please enter the random number seed.";
cin >> j;
srand(j);
for (i = 0; i < 10000000; i++)
ary[die() + die()]++;
for (i = 2; i <= 12; i++)
{
cout << setw(3) << i << " : " << setw(6) << ary[i] << " : ";
for (j = 0; j < ary[i]; j += 2000)
cout << "*";
cout << endl;
}
return 0;
}
EXAMPLE OUTPUT: https://imgur.com/a/tETCj4O
I know I need to do something with rand() % 6 + 1; in the beginning of the program. I feel like I am close to being complete but missing key points! I also realize I have not defnied die() in my ary[]
I recommend creating random seeds from high precision timers such as std::chrono::high_resolution_clock. Then they are not dependent on the user and are actually random. Create the seed always before calling std::rand.
#include <chrono>
auto time = std::chrono::high_resolution_clock::now();
auto seed = std::chrono::duration_cast<std::chrono::milliseconds>(time);
std::srand(seed)
Millisecond precision makes the seed usually unique enough but if the seed is required close to 1000 times a second then i recommend using nanosecond or microsecond precision to be really random.
Best would be to create a function that creates the random seed using high precision timer and the random value and finally makes sure the return value is between 0 and 5 (for 6 sided dice).

Having garbage numbers while calculating percentage

So, I hate to ask, but, I'm having some issue with this, I'm new to C++ and I'm just starting out. Everything is done for the most part. Expect for a little thing.
Line 35-36 should be calculating the average (Which for some reason, I haven't been able to get it to work.)
Line 41-47 should print out the percentage that heads/tails was landed on with precision to one decimal, and then print out the correct numbers of * to represent the percentage.
But, when I run it, my heads/tail count is messed up. As well as my percentage numbers. I'm just looking for a push in the right direction.
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <iomanip>
using std::cout; using std::cin; using std::endl;
using std::fixed; using std::setprecision;
int main()
{
srand(time(0));
int userInput,
toss,
headsCount,
tailsCount;
double headsPercent = 0,
tailsPercent = 0;
cout << "How many times do you want to toss the coin? ";
cin >> userInput;
while(userInput < 0)
{
cout << "Please enter a positive number: ";
cin >> userInput;
}
for(int i = 1; i < userInput; i++)
{
toss = rand() % 2;
if(toss == 0)
headsCount++;
else
tailsCount++;
}
headsPercent = userInput / headsCount * 100;
tailsPercent = userInput / tailsCount;
cout << "Heads: " << headsCount << endl
<< "Tails: " << tailsCount << endl << endl;
cout << "Heads Percentage: " << fixed << setprecision(1) << headsPercent << " ";
for(int b = 0; b < headsPercent; b++)
cout << "*";
cout << "\nTails Percentage: " << tailsPercent << " ";
for(int b = 0; b < tailsPercent; b++)
cout << "*";
return 0;
}
In addition to the uninitialized variables here, that others have pointed out, the calculations are all wrong.
Take out paper and pencil, and run some your own calculations the old-fashioned way.
Let's say there were five tosses, three heads, two tails. This means that (after fixing the uninitialized variables):
userInput=5
headsCount=3
tailsCount=2
Now, here's how you're calculating your supposed percentages:
headsPercent = userInput / headsCount * 100;
tailsPercent = userInput / tailsCount;
So, using your own numbers, you will get:
headsPercent = 5 / 3 * 100
tailsPercent = 5 / 2;
Does this look right to you? Of course not. You can do the arithmetic yourself. Divide 5 by 3 and multiply by 100. This is integer division, so five divided by three is 1, multiplied by 100 is 100. Five divided by two is two. So you get 100% and 2% here.
Of course, that's wrong. Two and three times, out of five, is 40% and 60%, respectively.
Writing a program means:
A) Figure out how calculations need to be made
B) Write the code to do the calculations.
You're still on step A. You need to figure out how you want to make these calculations so they're correct, first.
This has nothing really to do with C++. If you were using any other language, and coded this, in that manner, you'll get the same wrong answers.
The only thing this might have to do with C++ is that integer division, in C++ does not produce a fractional amount. It's integer division. But that's not your only problem.
Firstly u have to correct ur basics of mathematics.
Calculating %age means
example
(Marks obtained)/(Total marks)*100
Not (Total marks/marks obt)*100
Dividing any no by 0 is not defined. So if ur current code randomly assign toss or head =0, then obviously u will have errors.
Secondly talking about codes, U should either initialize i from 0 , or u should use
for (i=1; i<=userInput; i++)
As otherwise the head+toss value will be userInput-1.
Also remember to initialise variables like
Int headsCount=0;
etc. As the variable will take any random value if not initialised to a fixed no. (Though it does not creates a problem here)
And just change the datatype
int userInput,
toss,
headsCount,
tailsCount;
To
double userInput,
toss,
headsCount,
tailsCount;
This will solve your problem.
Advice: Please use
using namespace std;
in the starting of ur programs as u have to type a lot of std::
Welcome to C++. You need to initialise your variables. Your compiler should have warned you that you were using a variable without initialising it. When you don't initialise a value, your program has undefined behaviour.
I'm talking about headsCount and tailsCount. Something like this should be fine:
int headsCount = 0, tailsCount = 0;
Also note that your loop should start at 0, not 1, since you are using the < operator on the final condition.
Finally, your percentage calculations are backwards. It should be:
headsPercent = headsCount * 100 / userInput;
tailsPercent = tailsCount * 100 / userInput;
Now, there's a weird thing that might happen because you are using integer division. That is, your percentages might not add up to 100. What's happening here is integer truncation. Note that I dealt with some of this implicitly using the 100x scale first.
Or, since the percentages themselves are double, you can force the calculation to be double by casting one of the operands, thus avoiding integer truncation:
headsPercent = static_cast<double>(headsCount) / userInput * 100;
In fact, since the only two possibilities are heads and tails, you only need to count one of them. Then you can do:
tailsPercent = 100 - headsPercent;
1) This loop should start from 0:
for(int i = 1; i < userInput; i++)
2) The divisions are not correct:
//headsPercent = userInput / headsCount * 100;
//tailsPercent = userInput / tailsCount;
headsPercent = headsCount / userInput * 100;
tailsPercent = tailsCount / userInput * 100;
3) Finally:
cout << "\nTails Percentage: " << fixed << setprecision(1) << tailsPercent << " ";

How Can I Speed My C++ Program Up?

Basically I am relearning C++ and decided to create a lotto number generator.
The code creates the ticket and if that ticket does not already exist, it is added to a vector to store every possible combination.
The program works, but its just far too slow, adding an entry roughly every second, and It will get slower as it finds it more difficult to add unique combinations out of over 13 million possible combinations.
Anyway here is my code, any optimization tips would appreciated:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> lottoCombos;
const int NUMBERS_PER_TICKET = 6;
const int NUMBERS = 49;
const int POSSIBLE_COMBOS = 13983816;
string createTicket();
void startUp();
void getAllCombinations();
int main()
{
lottoCombos.reserve(POSSIBLE_COMBOS);
cout<< "Random Ticket: "<< createTicket()<< endl;
getAllCombinations();
for (int i = 0; i < POSSIBLE_COMBOS; i++)
{
cout << endl << lottoCombos[i];
}
system("PAUSE");
return 0;
}
string createTicket()
{
srand(static_cast<unsigned int>(time(0)));
vector<int> ticket;
vector<int> numbers;
vector<int>::iterator numberIterator;
//ADD AVAILABLE NUMBERS TO VECTOR
for (int i = 0; i < NUMBERS; i++)
{
numbers.push_back(i + 1);
}
for (int j = 0; j < NUMBERS_PER_TICKET; j++)
{
int ticketNumber = rand() % numbers.size();
numberIterator = numbers.begin()+ ticketNumber;
int nm = *numberIterator;
numbers.erase(numberIterator);
ticket.push_back(nm);
}
sort(ticket.begin(), ticket.end());
string result;
ostringstream convert;
convert << ticket[0] << ", " << ticket[1] << ", " << ticket[2] << ", " << ticket[3] << ", " << ticket[4] << ", " << ticket[5];
result = convert.str();
return result;
}
void getAllCombinations()
{
int i = 0;
cout << "Max Vector Size: " << lottoCombos.max_size() << endl;
cout << "Creating Entries" << endl;
while ( i != POSSIBLE_COMBOS )
{
bool matchFound = true;
string newNumbers = createTicket();
for (int j = 0; j < lottoCombos.size(); j++)
{
if ( newNumbers == lottoCombos[j] )
{
matchFound = false;
break;
}
}
if (matchFound != false)
{
lottoCombos.push_back(createTicket());
i++;
cout << "Entries: "<< i << endl;
}
}
sort(lottoCombos.begin(), lottoCombos.end());
cout << "\nCombination generation complete!!!\n\n";
}
The reason each lottery ticket is taking a second to generate is because you are misusing srand(). By calling srand(time(0)) every time createTicket() is called, you ensure that createTicket() returns the same numbers every time it is called, until the next time the value returned by time() changes, i.e. once per second. So your reject-duplicates algorithm will almost always find a duplicate until the next second goes by. You should move your srand(time(0)) call to the top of main() instead.
That said, there are perhaps larger issues to confront here: my first question would be, is it really necessary to generate and store every possible lottery ticket? (and if so, why?) IIRC real lotteries don't do that when issuing a ticket; they just generate some random numbers and print them out (and if there are multiple winning tickets printed with the same numbers, the owners of those tickets share the prize money).
Assuming you do need to generate every possible lottery ticket for some reason, there are better ways to do it than randomly. If you've ever watched the odometer increment while driving a car, you'll get the idea for how to do it linearly; just imagine an odometer with 6 wheels, where each wheel has 49 different possible positions it can be in (rather than the traditional 10).
Finally, a vector has O(N) lookup time, and if you are doing a lookup in the vector for every value you generate, then your algorithm has O(N^2) time, which is to say, it's going to get really slow really quickly as you generate more tickets. So if you have to store all known tickets in a data structure, you should definitely use a data structure with quicker lookup times, for example a std::map or a std::unordered_set, or even a std::bitset as suggested by #RedAlert.

String compression and comparison

Recently, I started writing a program to compare DNA sequence. As the alphabet only consists of four letters (ATCG), compressing each character to 2 bits seemed like it would offer faster comparisons (are two characters the same or different). However, when I ran a test char comparisons were much faster than bit comparisons (by ~30%). Compression was carried out in both programs as a control. What am I missing here? Is there a more efficient way to compare bits?
p.s. I also tried vector, but it was a bit slower than bitset.
// File: bittest.cc
// Test use of bitset container
#include <ctime>
#include <iostream>
#include <bitset>
#include <vector>
#include <string>
using namespace std;
void compress(string&, bitset<74>&);
void compare(bitset<74>&, bitset<74>&);
int main()
{
// Start timer
std::clock_t start;
double difference;
start = std::clock();
for(int i=0; i<10000000; ++i){
string frag1="ATCGACTGACTGACTGACTGACTGACTGACTGACTGA";
string frag2="AACGAACGAACGAACGAACGAACGAACGAACGAACGA";
int a=37;
bitset<74> bits1;
bitset<74> bits2;
compress(frag1, bits1);
compress(frag2, bits2);
compare(bits1, bits2);
}
difference = ( std::clock() - start ) / (double)CLOCKS_PER_SEC;
int minutes = difference/60;
int seconds = difference - minutes * 60;
if (seconds < 10){
cout << "\nRunning time: " << minutes << ":0" << seconds << endl << endl;
}else{
cout << "\nRunning time: " << minutes << ":" << seconds << endl << endl;
}
return 0;
}
void compress(string& in, bitset<74>& out){
char c;
int b=0;
for(int i=0; i<in.length(); ++i){
c=in[i];
b=2*i;
switch(c){
case 'A':
break;
case 'C':
out.set(b+1);
break;
case 'G':
out.set(b);
break;
case 'T':
out.set(b);
out.set(b+1);
break;
default:
cout << "Invalid character in fragment.\n";
}
}
}
void compare(bitset<74>& a, bitset<74>& b){
for(int i=0; i<74; ++i){
if(a[i] != b[i]){
}
}
}
And the string harness...
// File: bittest.cc
#include <ctime>
#include <iostream>
#include <bitset>
#include <vector>
#include <string>
using namespace std;
void compress(string&, bitset<74>&);
void compare(string&, string&);
int main()
{
// Start timer
std::clock_t start;
double difference;
start = std::clock();
for(int i=0; i<10000000; ++i){
string frag1="ATCGACTGACTGACTGACTGACTGACTGACTGACTGA";
string frag2="AACGAACGAACGAACGAACGAACGAACGAACGAACGA";
int a=37;
bitset<74> bits1;
bitset<74> bits2;
compress(frag1, bits1);
compress(frag2, bits2);
compare(frag1, frag2);
}
difference = ( std::clock() - start ) / (double)CLOCKS_PER_SEC;
int minutes = difference/60;
int seconds = difference - minutes * 60;
if (seconds < 10){
cout << "\nRunning time: " << minutes << ":0" << seconds << endl << endl;
}else{
cout << "\nRunning time: " << minutes << ":" << seconds << endl << endl;
}
return 0;
}
void compress(string& in, bitset<74>& out){
char c;
int b=0;
for(int i=0; i<in.length(); ++i){
c=in[i];
b=2*i;
switch(c){
case 'A':
break;
case 'C':
out.set(b+1);
break;
case 'G':
out.set(b);
break;
case 'T':
out.set(b);
out.set(b+1);
break;
default:
cout << "Invalid character in frag.\n";
}
}
}
void compare(string& a, string& b){
for(int i=0; i<37; ++i){
if(a[i] != b[i]){
}
}
}
Consider the two comparison routines:
void compare(bitset<74>& a, bitset<74>& b){
for(int i=0; i<74; ++i){
if(a[i] != b[i]){
}
}
}
and
void compare(string& a, string& b){
for(int i=0; i<37; ++i){
if(a[i] != b[i]){
}
}
}
Right off the bat you can see that one is executing the loop 74 times and the other is executing the loop 37 times. So already the bitset approach is starting from a position of weakness.
Now consider the types of data being accessed; accessing individual bytes is reasonably quick; accessing individual bits from any data structure might store a single bit in an entire byte or maybe even some larger word size. If it stores bits in individual bits, then some bitmasking operations must be introduced, and those all take processing power too. If the bits are stored in bytes, then you are in fact comparing only half of each character on each bit. If the bits are stored in words or larger, you are increasing the size of the CPU's data cache -- potentially taking something that might fit entirely in one cache line to several cache lines. That's a potential for gigantic speed penalties, though on inputs this small, it's probably not too horrible yet.
If you replace your bitset with a char[] that is large enough to hold all your data, manually set the bits yourself in the compression routines, and then compare the char[] array a byte at a time or larger, you can probably drastically improve the speed of the comparison routines. Will the speed up be sufficient to overcome the cost of the compression routines? That's tough to say and depends in part upon how many comparisons you can make with each compressed form.
If you can perform your comparison using int or larger datatypes, you can probably go even significantly faster, as modern CPUs are usually faster at accessing 4-bytes or 8-bytes at a time than 1-byte at a time. Most strcmp(3) or memcmp(3) routines are optimized to perform huge, aligned reads. If you use memcmp(3) to do your comparison, you'll have the best chance of going at top speed -- and that goes for both the compressed and uncompressed versions.
The CPU will not load anything smaller than a byte, which is eight bits. Therefore, when your program treats a pair of bits, the CPU actually loads eight bits, then masks the unused six out. The masking operation takes processor time.
You must trade memory-usage efficiency against execution time. Which you prefer is your choice.