Question

timing a function in milliseconds in c++

Asked by: intrigue63

I am trying test different algorithms for various math algorithms and I need to time them so I can use the fastest ones. I cant find what I need to do this.. on what I have I just get 0. I am using only a square root function on this example. I know it to be accurate, but I want to see if it is faster than the math library function sqrt().

#include <iostream>
#include <time.h>
#include "sqRoot.h"
using namespace std;
 
int main()   {
	
        clock_t start, end;
	double rtime = 0;
 
	start = clock();
 
	//timed function
	double Number = 100000;
	double Nbr    = sqRoot::sqrt1(Number);
 
 
	end = clock();
 
 
	//printout
	rtime = (end - start/ CLOCKS_PER_SEC)/1000;
	cout << "The square root of " << Number << " is " << Nbr << "\n\n";
  	cout<< rtime <<'\n';
 
 
	return 0;
}

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-03-10 at 13:25:28ID24217634
Tags

timing

,

c++

,

milliseconds

Topics

Windows ATL / WTL / COM Programming

,

C++ Programming Language

,

Miscellaneous Programming

Participating Experts
5
Points
500
Comments
34

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Sqrt
    Hi Anyone I can call the Sqr function in a VB project ok. How do I call the Sqrt function? Dim mySqrt As Double mySqrt = 18 mySqrt = (Sqr(mySqrt)) Regards admoller
  2. Fastest Bresenham algorithm
    Hi Experts, I've read one in a book, there is the most fastest line algorithm founded by two university guys, I don't remember the name but their algorithm is based on improved Bresenham. So please can someone create a line function which I can simply use based on that fast...
  3. Help with Sqrt
    Hi guys, Still trying to learn visual basic and getting nowhere fast. I've been trying to write a little program that will work out the closest intersection points of 2 arcs. I can't remember the formula for intersecting circles so i got lazy and got the formula for the clos...
  4. to find square root of a number
    how to find square root of a number without using sqrt function
  5. Fastest prime searching algorithm
    I'm bored. I decided i'd like to calculate the first billion primes, just for fun, and to slowly fill up my boss's hard drive. My current algorithm is really really basic, and probably slow, as its designed to be able to pick up where it left off if i stop it and resume it....

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: rafael_accPosted on 2009-03-11 at 02:35:22ID: 23855091

The problem is that clock() returns a clock_t type, which I believe is a long int (I think!).
Try this instead:

time_t start, end;
double dif;

time (&start); -> Here you get the time (before your code starts)
/* YOUR CODE HERE */
time (&end); -> Here you get the time (after your code ends)
dif = difftime (end, start);

I think this code will work

 

by: mrjoltcolaPosted on 2009-03-11 at 21:27:31ID: 23864817

You might consider using a profiler. Here is a link to a PAQ

http://www.experts-exchange.com/Programming/Languages/CPP/Q_22802566.html

 

by: Infinity08Posted on 2009-03-12 at 00:20:36ID: 23865554

>>         rtime = (end - start/ CLOCKS_PER_SEC)/1000;

If you change this line to :

        rtime = (((double) (end - start)) / CLOCKS_PER_SEC) * 1000.0;

you'll get the elapsed time in milliseconds. However, it won't be with millisecond precision, since the system clock usually doesn't have that kind of precision (it's often in the order of 20 ms).


What is often done, is to run the same code 1000 times, and then use a timer with at least second precision, and divide the result by 1000

 

by: peprPosted on 2009-03-12 at 01:40:57ID: 23865889

Programming for Windows, you probably want to use the QueryPerformanceCounter() and the related functions. See the snippet below.

Just to illustrate, in my case I get the results like

0.0486095 ms (696 cnt)

// Let's define variables for measuring the time
// of XYZ
LARGE_INTEGER timeBegin;
LARGE_INTEGER timeEnd;
 
QueryPerformanceCounter(&timeBegin);
XYZ();
QueryPerformanceCounter(&timeEnd);
 
.... and then evaluate the results by calling the following.
 
std::string ElapsedTimeAsString(LARGE_INTEGER & countStart,
                                LARGE_INTEGER & countStop)
{
    ostringstream ostResult;
    ostResult <<
        "Error: High-resolution performance counter is not supported.";
    
    LARGE_INTEGER largeiFreq;
    
    if (QueryPerformanceFrequency(&largeiFreq)) 
    {
        // Calculate the correction for the call of the 
        // QueryPerformanceCounter();
        // 
        LARGE_INTEGER c1, c2;
        QueryPerformanceCounter(&c1);
        QueryPerformanceCounter(&c2);
        long liCorrection = c2.LowPart - c1.LowPart;
 
        // Assume, that the HighPart of both counters is equal.
        //
        long liElapsed = countStop.LowPart - countStart.LowPart
                         - liCorrection;
        DWORD liFreq = largeiFreq.LowPart;
            
        ostResult.str("");
        ostResult << (liElapsed * 1000.0 / liFreq) << " ms ("
                  << liElapsed << " cnt)";
    }
    
    return ostResult.str();
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:

Select allOpen in new window

 

by: peprPosted on 2009-03-12 at 01:56:57ID: 23865957

The case could be that your function is really fast. Then repeat it say 100000 times. To do timing corrections, implement the same function with simpler body (basically empty but ensure its call is not optimized out) and run the same test (the same times). Then you can compare the results.

The above snippet tailored to your code is shown below (the repetition not done here).

#include <Windows.h>
#include <iostream>
#include <sstream>
#include <string>
 
#include "sqRoot.h"
 
using namespace std;
 
std::string ElapsedTimeAsString(LARGE_INTEGER & countStart,
                                LARGE_INTEGER & countStop);
 
 
int main() 
{
        
    LARGE_INTEGER timeBegin;
    LARGE_INTEGER timeEnd;
 
    double Number = 100000;
    double Nbr = 0.0;
    
    QueryPerformanceCounter(&timeBegin);
    Nbr = sqRoot::sqrt1(Number); //timed function
    QueryPerformanceCounter(&timeEnd);
 
    //printout
    cout << "The square root of " << Number << " is " << Nbr << "\n\n";
    cout<< ElapsedTimeAsString(timeBegin, timeEnd) <<'\n';
 
    return 0;
}
 
 
std::string ElapsedTimeAsString(LARGE_INTEGER & countStart,
                                LARGE_INTEGER & countStop)
{
    ostringstream ostResult;
    ostResult <<
        "Error: High-resolution performance counter is not supported.";
    
    LARGE_INTEGER largeiFreq;
    
    if (QueryPerformanceFrequency(&largeiFreq)) 
    {
        // Calculate the correction for the call of the 
        // QueryPerformanceCounter();
        // 
        LARGE_INTEGER c1, c2;
        QueryPerformanceCounter(&c1);
        QueryPerformanceCounter(&c2);
        long liCorrection = c2.LowPart - c1.LowPart;
 
        // Assume, that the HighPart of both counters is equal.
        //
        long liElapsed = countStop.LowPart - countStart.LowPart
                         - liCorrection;
        DWORD liFreq = largeiFreq.LowPart;
            
        ostResult.str("");
        ostResult << (liElapsed * 1000.0 / liFreq) << " ms ("
                  << liElapsed << " cnt)";
    }
    
    return ostResult.str();
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:

Select allOpen in new window

 

by: peprPosted on 2009-03-12 at 02:05:23ID: 23865996

For sqrt from <math.h> it gives me on my computer

|The square root of 100000 is 316.228
|
|0.000209524 ms (3 cnt)

Notice that you should not believe the precision of 0.000209524 here. The 3 ticks of the counter is much more accurate view here. In other words, the function should be tested in the loop to get more accurate comparison.

When testing your function against the existing function, you want to have some relation, not neccessarily the exact time. If you only want to determine "slower/faster", then the looped testing is easier (no need to make a correction for the code that implements the loop).

 

by: rafael_accPosted on 2009-03-12 at 02:07:37ID: 23866010

Have you tried the code I gave you - not trying to be funny but it may just give you what you need!

 

by: Infinity08Posted on 2009-03-12 at 02:17:45ID: 23866078

@rafael_acc : difftime returns a difference in seconds, not milliseconds.

 

by: itsmeandnobodyelsePosted on 2009-03-12 at 05:00:16ID: 23867182

>>>> If you change this line to :
>>>>      rtime = (((double) ) / CLOCKS_PER_SEC) * 1000.0;

On 32 bit Windows it simply is

    int diff = (end - start);

and gives milliseconds.

The accuracy of clock() is between 15 and 16 milliseconds.

>>>> What is often done, is to run the same code 1000 times,

Normally you would need a million times or more on modern hardware to get run times greater 15 milliseconds.

And there is some more issue that the compiler will optimize such a loop if the results do not change in the loop or if the result calculated in the loop was not used below later. So, you might need to sum up the sqare root within the loop and print the sum later to not being trapped by the optimizer.

 

by: Infinity08Posted on 2009-03-12 at 05:09:15ID: 23867249

>> On 32 bit Windows it simply is

That would only make sense of CLOCKS_PER_SEC has the value 1000. Is that the case ?

Even if that is so, why not do it properly, and make the code correct for any compiler/platform ?

 

by: peprPosted on 2009-03-12 at 05:59:33ID: 23867678

>> why not do it properly, and make the code correct for any compiler/platform ?

Well, it is possible to make the code nicely written and portable. On the other hand, intrigue63 wants to test a function that takes much less time than the clock() resolution. If one is making an application for Windows... The pragmatic approach is "if it can be done better, do it better". The QueryPerformanceCounter() has much smaller resolution. It can be obtained using QueryPerformanceFrequency() (and is use inside the ElapsedTimeAsString()). It returns ticks per second. On my computer (Windows Vista, Intel Core 2 Duo 6420, 2.13 GHz) it does 14318180 ticks per second, i.e. resolution about 0.07 microseconds.

The call of the QueryPerformanceCounter() takes about 11 ticks -- hence the correction for the call inside the ElapsedTimeAsString().

 

by: Infinity08Posted on 2009-03-12 at 06:01:24ID: 23867695

@pepr : my post was in response to Alex, not you ;)

 

by: peprPosted on 2009-03-12 at 06:56:11ID: 23868273

Infinity08: Yes, I know. You have cited him. ;) I usually try to write towards the asker, not against some other reasoning or comments. I only wanted to emphasize that it could be reasonable to use the platform-specific solution. And I wanted to show that usage of performance counters on Windows can be usefull in this case, and I wanted to illustrate why it is usefull.

 

by: itsmeandnobodyelsePosted on 2009-03-12 at 08:16:03ID: 23869324

>>>> That would only make sense of CLOCKS_PER_SEC has the value 1000. Is that the case ?

I would assume so cause I never did it differently in the last 15 years ;-)

>>>> why not do it properly, and make the code correct for any compiler/platform ?

It is properly on Windows while the first approach of intrig63 was wrong. IMO, for testing purposes you should make it stupid simple and don't spoil the tests with portability considerations that are currently off-topic.  

 

by: itsmeandnobodyelsePosted on 2009-03-12 at 08:30:13ID: 23869531

>>>> The QueryPerformanceCounter() has much smaller resolution.
Yes, I think a better timer is appropriate though I never used QueryerformanceTimer myself.

Is it available with standard installation of VC Pro?

Does the timer itself make any impact on the measured time?

 

by: Infinity08Posted on 2009-03-12 at 08:50:27ID: 23869835

>> IMO, for testing purposes you should make it stupid simple and don't spoil the tests with portability considerations that are currently off-topic.

It's not about portability. It's about correctness. It's not because your current platform uses the value 1000, that the next version will use that value, nor does it mean that intrigue63's platform uses that value.

This value (1000) is documented nowhere (at least I couldn't find it), and seems to be an assumption you made, probably based on an observation of the behavior for your platform(s).
If the code will only ever run on Microsoft platforms, there still is no guarantee that CLOCKS_PER_SEC equals 1000, now and/or in the future.

Here's the MSDN reference for the clock function :

        http://msdn.microsoft.com/en-us/library/4e2ess30.aspx

CLOCKS_PER_SEC is explicitly mentioned, and explicitly used in the example code (as it should). But there is no mention of CLOCKS_PER_SEC being equal to 1000.


Imo, giving a correct solution (that is guaranteed to always work) is better than giving a solution that might work right now on a specific platform, but might fail tomorrow.
After all, learning it the right way is easier (and more efficient) than having to un-learn bad habits.

 

by: peprPosted on 2009-03-12 at 11:34:59ID: 23871924

itsmeandnobodyelse: >> Is it available with standard installation of VC Pro?

The functions are in the Windows kernel (kernel32.dll) and are available since Windows 95 and Windows NT 3.1. Here is the documentation: http://msdn.microsoft.com/en-us/library/ms644904(VS.85).aspx, http://msdn.microsoft.com/en-us/library/ms644905(VS.85).aspx. It should be available wherever you can include Windows.h and link kernel32.lib.

>> Does the timer itself make any impact on the measured time?

The documentation for the QueryPerformanceFrequency() says: "If the installed hardware supports a high-resolution performance counter, the return value is nonzero. If the function fails, the return value is zero."

But definitely, getting the counter value takes some time. Because of that I did the simple correction for the QueryPerformanceCounter() function call inside my implementation of the ElapsedTimeAsString() -- see http:#23865957 lines 46-52 and 57. The truth is that it is rather sloppy implementation because it does not use the higher part of the LARGE_INTEGER. This way it occasionally can produce very surprising (and very wrong) result -- when the first QueryPerformanceCounter() was called before overflow of the highest bit from lower part and the second QueryPerformanceCounter() after incrementing the higher part.

Infinity08: I may be wrong, but I guess that the 1000 comes from converting seconds to miliseconds. If CLOCKS_PER_SEC means what it says then  clock_ticks / CLOCKS_PER_SEC means the number of seconds. Multiplied by 1000 means number of miliseconds (invariantly on what is the value of the CLOCKS_PER_SEC. Basically, it is exactly the same in principle as using the high resolution timer values and the frequency obtained via QueryPerformanceFrequency().

 

by: Infinity08Posted on 2009-03-12 at 11:38:44ID: 23871962

Of course, pepr, but this is still about Alex's suggestion that :

    int diff = (end - start);

gives a value in milliseconds. If CLOCKS_PER_SEC equals 1000, then it does. If CLOCKS_PER_SEC has a different value, it doesn't. My point is that you shouldn't assume that CLOCKS_PER_SEC equals 1000, since there's no guarantee for that. Not even in the Microsoft documentation.

 

by: peprPosted on 2009-03-12 at 12:37:07ID: 23872585

Infinity08: Oh, I see. I did not noticed that.

 

by: intrigue63Posted on 2009-03-16 at 13:41:37ID: 31556460

Thanks a million! I am running on both windows and Linux so both solutions worked

 

by: Infinity08Posted on 2009-03-16 at 13:44:44ID: 23902224

Didn't you want the result in milliseconds, intrigue63 ? The accepted answer gives a result in seconds.

 

by: itsmeandnobodyelsePosted on 2009-03-16 at 14:50:17ID: 23902824

>>>> This value (1000) is documented nowhere (at least I couldn't find it), and seems to be an assumption you made,
Sorry, the statement I posted did work over ten or even fifteen years. I didn't make any assumption cause I used the clock function before knowing of the CLOCKS_PER_SEC macro. If it ever wouldn't work on a platform I easily would recognize that the result is wrong if for example the result would be suddenly in microseconds. It would be strange but surely I would be able to correct it. Hence, correctness never was in danger ;-)  

There are more dangerous assumptions than assuming clock will return milliseconds on Windows platform. For example any bit shift operation on a unsigned integer probably will assume a 32bit integer. Also I don't know any non-trivial program which wouldn't have problems with a 16bit char type. What is with header files where each compiler may have its own philosophy and where there a only a few standards cross-platform? Shouldn't we set the focus to the real problems but being stubborn on searching problems where there are none?

 

by: itsmeandnobodyelsePosted on 2009-03-16 at 14:55:31ID: 23902861

>>>> The accepted answer gives a result in seconds.

That's what I wanted to say. When using the CLOCKS_PER_SEC it is a much bigger chance that the results were wrong for an unexperienced developer that it ever could be assuming clock will return milliseconds.

 

by: Infinity08Posted on 2009-03-17 at 04:33:07ID: 23906687

Alex, there's no point in arguing over this, since you have your idea, and I have mine.

Let me just state that using CLOCKS_PER_SEC to interpret the value returned by clock() is the only correct way to do things. Anything else relies on assumptions, and is thus not reliable.

Since this question can be read by many people with different platforms/environments, now and for years to come, I maintain that suggesting to ignore CLOCKS_PER_SEC, and assume that it has the value 1000 is dangerous.

Furthermore, it might be true that Microsoft platforms have CLOCKS_PER_SEC set to 1000, but that is documented nowhere, and could change with any next version of their compiler and/or C runtime. So, even on Windows, it's not recommended to make assumptions about its value.


That's it. Unless intrigue63 wants to clarify his choice of the accepted reply, I'm out of here ;)

 

by: itsmeandnobodyelsePosted on 2009-03-17 at 04:59:32ID: 23906889

>>>> I maintain that suggesting to ignore CLOCKS_PER_SEC, and assume that it has the value 1000 is dangerous.

I maintain that using a function like clock not necessarily implies to making any thoughts about CLOCKS_PER_SEC or considering methods to normalise the return value. If your program requires such a normalisation things are different. But I couldn't see such a requirement for a simple test program. Hence, it is just a 'doing things where no problem exists' what indeed is dangerous (as the sample proves).

 

by: intrigue63Posted on 2009-03-17 at 11:25:50ID: 23910912

Ok this is what works on Linux:

#include <iostream>
#include <time.h>
#include <math.h>
#include "mymath.h"

using namespace std;

int main()   {
      
        clock_t start, end;
      double rtime = 0;
        double num;
      double Number = 100000;

 
        //c-lib sqrt(num)
        start = time(0);

      num = sqrt(Number);

      end = time(0);
      rtime = (end - start / CLOCKS_PER_SEC);

      //printout
      cout << "sqRoot(" << Number << ") is " << num << "\n\n";
        cout<< rtime <<'\n';
      rtime = 0;

      //my sqrt1(n)

      start = time(0);

      num = mymath::sqrt1(Number);

      end = time(0);
      rtime = (end - start / CLOCKS_PER_SEC);

      //printout
      cout << "sqRoot1(" << Number << ") is " << num << "\n\n";
        cout<< rtime <<'\n';



 output:
charybdis[12]% ./run
sqRoot(100000) is 316.228

1.23731e+09
sqRoot1(100000) is 316.228

 

by: Infinity08Posted on 2009-03-17 at 11:32:51ID: 23910979

>> Ok this is what works on Linux:

It's not really correct though :)

For example, time(0) returns a time_t, not a clock_t. It's clock() that returns a clock_t.

In this line :

>>       rtime = (end - start / CLOCKS_PER_SEC);

division has higher priority than subtraction, so what you do is this :

            rtime = (end - (start / CLOCKS_PER_SEC));

which is not really what you wanted.



So, it seems that you don't have your answer yet, even though you've already closed the question. You can request to get the question re-opened (click the "Request Attention" link, and explain that you want to re-open the question), so we can help you further, and ultimately, you can accept those posts that answered your question.


Allow me to refer back to my earlier post http:#23865554 where I showed the correct use of clock() to get an elapsed time in milliseconds. Just replace that line in your original code (the code you posted in your question), and see what result you get.

 

by: intrigue63Posted on 2009-03-17 at 11:47:55ID: 23911139

ok with
rtime = (end - start / CLOCKS_PER_SEC);

output:
charybdis[21]% make
g++ -c -g -Wall main.cpp
g++ -o run main.o mymath.o
charybdis[22]% ./run
sqRoot(100000) is 316.228

1.23731e+09
sqRoot1(100000) is 316.228

1.23731e+09
charybdis[23]%


output with line:  rtime = (end - (start / CLOCKS_PER_SEC));

charybdis[24]% ./run
sqRoot(100000) is 316.228

1.23731e+09
sqRoot1(100000) is 316.228

1.23731e+09
charybdis[25]%

output with line   rtime = (((double) (end - start)) / CLOCKS_PER_SEC) * 1000.0;

sqRoot(100000) is 316.228

0
sqRoot1(100000) is 316.228

1.23731e+09
charybdis[27]%

hmmmm

btw thanks for checking this out

 

by: Infinity08Posted on 2009-03-17 at 11:51:50ID: 23911195

>> ok with
>> rtime = (end - start / CLOCKS_PER_SEC);

Is incorrect as I said earlier.


>> output with line:  rtime = (end - (start / CLOCKS_PER_SEC));

Is exactly the same, so it's also incorrect.


>> output with line   rtime = (((double) (end - start)) / CLOCKS_PER_SEC) * 1000.0;

Is only correct if end and start are values returned by clock(). Are they ?

Did you use your original code as I suggested ?


Note also that if you only measure one execution of the sqrt function, it might be over too fast to be measurable. Try putting the sqrt call in a loop that executes 1000 or 1000000 times, and measure how long it takes to execute the entire loop.

 

by: intrigue63Posted on 2009-03-17 at 13:32:13ID: 23912592

thanks Infinity08, I overlooked something simple I changed the time(0) to clock() I forgot to do that and I put everythin g in a for loop as you suggested. and changed my number to calculate random numbers. a coleague of mine said that the compiler cached the results in optimization and that was another issue.
 so this is what I did:


using namespace std;

int main()   {
      
        clock_t start, end;
      double rtime = 0;
        double num;
      double Number;
      int i;
 
      srand(time(NULL));

        //c-lib sqrt(num)
        start = clock();
      for(i=0; i < 1000000; i++){
            Number = (rand() / (RAND_MAX + 1.0)) * 102000000.0;
            num = sqrt(Number);
      }
      end = clock();
      rtime = ((((double) end - start) / CLOCKS_PER_SEC) * 1000.0);

      //printout
      cout << "sqRoot(random number) ran 1000000 times " << '\n';
        cout<< "ran in " << rtime << " units of measurement." << '\n';
      rtime = 0;

      //my sqrt1(num)

      start = clock();
      for(i=0; i < 1000000; i++){
            Number = (rand() / (RAND_MAX + 1.0)) * 102000000.0;
            num = mymath::sqrt1(Number);
      }
      end = clock();
      rtime = ((((double) end - start) / CLOCKS_PER_SEC) * 1000.0);

      //printout
      cout << "sqRoot(random number) ran 1000000 times " << '\n';
        cout<< rtime <<'\n';



      //my sqrt2(num)

      start = clock();
      for(i=0; i < 1000000; i++){
            Number = (rand() / (RAND_MAX + 1.0)) * 102000000.0;
            num = mymath::sqrt1(Number);
      }
      end = clock();
      rtime = ((((double) end - start) / CLOCKS_PER_SEC) * 1000.0);

      //printout
      cout << "sqRoot(random number) ran 1000000 times " << '\n';
        cout<< rtime <<'\n';


      rtime = 0;
      return 0;

output for three different square root functions:

sqRoot(random number) ran 1000000 times
ran in 10 units of measurement.
sqRoot(random number) ran 1000000 times
240
sqRoot(random number) ran 1000000 times
230

 

by: Infinity08Posted on 2009-03-17 at 14:06:58ID: 23913045

>> sqRoot(random number) ran 1000000 times
>> ran in 10 units of measurement.
>> sqRoot(random number) ran 1000000 times
>> 240
>> sqRoot(random number) ran 1000000 times
>> 230

So, they both finished in around 230-240 ms, while the standard sqrt function finished in around 10 ms (quite a bit faster it seems).


>> a coleague of mine said that the compiler cached the results in optimization and that was another issue.

Yes, that's possible. To avoid that, try compiling the code without optimization (change the compiler flags for that).

 

by: intrigue63Posted on 2009-03-17 at 14:18:34ID: 23913207

thanks again for your help and thanks to everyone else's consideration too

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...