How can I measure how many milliseconds have elapsed?

I want to, for example, know how many milliseconds have elapsed while the user is inputing something. I tried clock(), but it always results in 0.
You could try GetTickCount() if you're using windows.
Last edited on
First: include the winmm.lib

 
#pragma comment(lib, "winmm.lib"); 


Second: before you use the cin command get the milliseconds elapsed until then from the start of the program using the method timeGetTime() and keep it intro a double, and in a second double keep the elapsed seconds until then from the start of the program, and substract from it the first double to get the time taken by the user to input

1
2
3
4
5
...
double untilNow = timeGetTime();
std::cin >> anything;
double timeTaken = timeGetTime() - untilNow;
...
Thank you. But I wonder if there is a way that can work under both Linux and Windows?
1
2
3
4
unsigned t0=clock();
//user input
unsigned elapsed=clock()-t0;
//Note: to convert to seconds, divide by CLOCKS_PER_SEC. 
1
2
3
4
unsigned t0=clock();
//user input
unsigned elapsed=clock()-t0;
//Note: to convert to seconds, divide by CLOCKS_PER_SEC. 

This doesn't work. I just always get zero when there is user input between the two clock().
Any other ideas?
It's working for me.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <ctime>

int main(){
    int a;
    unsigned t0=clock();
    std::cin >>a;
    unsigned elapsed=clock()-t0;
    std::cout <<elapsed<<std::endl;
}
You are using Windows, aren't you? Just now I tried it under Windows and it worked. But under my Ubuntu 9.04, it won't work at all.
Apparently, Linux implements clock() by measuring how much CPU time the program has used. Since I/O doesn't consume CPU time...
I think it should work if you replace "clock()" with "time(0)". You'll get the number of seconds.

EDIT: It does work.
Last edited on
I see and thank you.
time(0) works, but not as accurate as I want.
Now I am using system("date") to get the time. But I don't like it. So, under Linux, how can I get the accurate time except using system()? I mean, how does the command date do it?
Topic archived. No new replies allowed.