Why Am I Getting Different Time Values - c++

I've tried this code in C++ on Win7x64 platform with MSVC++, and I got CPU frequency about 2900000 ticks per second.
When I run this program, my stopwatch returns about 10,000,000 tick, which means it take about 4 seconds to process my program, but my program results are ready for me in 1 second (or less) O_o.
Could you please tell me what is wrong in my code?
#include <iostream>
#include "header.h"
#include <fstream>
#include <string>
#include <sstream>
#include <strsafe.h>
#include <direct.h>
#include <string.h>
using namespace std;
#define CV_TO_NANO 1000000000
#define CV_TO_MICRO 1000000
#define CV_TO_MILLI 1000
unsigned __int64 inline GetRDTSC()
{
__asm
{
; Flush the pipeline
XOR eax, eax
CPUID
; Get RDTSC counter in edx:eax
RDTSC
}
}
unsigned __int64 RunTest(TCHAR *AppName, TCHAR *CmdLine);
void main()
{
unsigned __int64 start = 0;
unsigned __int64 stop = 0;
unsigned __int64 freq = 0;
float rps;
ofstream dataFile;
// get processor freq
QueryPerformanceFrequency((LARGE_INTEGER *)&freq);
cout <<"freq (count per second): "<< freq << endl;
// round per second
rps = 1.0/(freq);
cout <<"rps (1/rps): "<< rps << endl;
dataFile.open ("d:/dataC.txt",ios::out );
for(int i = 0;i<200;i++)
{
SetProcessAffinityMask(GetCurrentProcess(),0x0001);
SetThreadAffinityMask(GetCurrentThread(),0x0001);
cout << RunTest(L"D:\\Child\\Child.exe", NULL);
}
getchar();
return;
}
unsigned __int64 RunTest(TCHAR *AppName, TCHAR *CmdLine)
{
unsigned __int64 start = 0;
unsigned __int64 stop = 0;
PROCESS_INFORMATION processInformation;
STARTUPINFO startupInfo;
memset(&processInformation, 0, sizeof(processInformation));
memset(&startupInfo, 0, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
BOOL result;
start = GetRDTSC();
result = ::CreateProcess(AppName, CmdLine, NULL, NULL, FALSE, REALTIME_PRIORITY_CLASS, NULL, NULL, &startupInfo, &processInformation);
stop = GetRDTSC();
getchar();
if (result == 0)
{
wprintf(L"ERROR: CreateProcess failed!");
}
else
{
WaitForSingleObject( processInformation.hProcess, 0 );
CloseHandle( processInformation.hProcess );
CloseHandle( processInformation.hThread );
}
return stop - start;
}

I think you have a misconception here that QueryPerformanceFrequency is telling you something about the speed of your processor - it isn't. QueryPerformanceFrequency retrieves the frequency of the high-resolution performance counter, which is not guaranteed to have any predictable relationship to your CPU clock speed. This value needs to be used in conjunction with QueryPerformanceCounter in order to get quality timing values, not with assembly that directly queries the RDTSC.

Here is an example of how to use the high-frequency timer to time a block of code:
#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
LARGE_INTEGER li = {};
__int64 freq, start, stop;
QueryPerformanceFrequency(&li);
freq = li.QuadPart;
cout << "Counter Frequency: " << freq << "\n";
QueryPerformanceCounter(&li);
start = li.QuadPart;
for( int i = 0; i < 1000000; ++i )
{
int n = i * rand();
}
QueryPerformanceCounter(&li);
stop = li.QuadPart;
double elapsed_seconds = static_cast<double>(stop-start) / static_cast<double>(freq);
cout << "Elapsed Time: " << elapsed_seconds << " seconds\n";
}

Related

Suspended thread time

I wanted to calculate the time between creating a thread and taking control by it, then compare this time for normal and suspended threads. But the results are quite chaotic.
So, my question is: Does it really makes sense? I think that instant resuming doesn't have a visible effect on the result.
#include <iostream>
#include <windows.h>
using namespace std;
DWORDLONG freq;
DWORD WINAPI startThread(LPVOID lpParam) {
DWORDLONG c_beg = *((DWORDLONG*)lpParam);
DWORDLONG c_end;
QueryPerformanceCounter((LARGE_INTEGER*)&c_end);
cout << (double(c_end - c_beg)) / (freq) << endl;
return 0;
}
int main()
{
DWORDLONG c_beg;
HANDLE iThread, sThread;
QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
cout << "instant" << endl;
for (int i = 0; i < 10; i++) {
QueryPerformanceCounter((LARGE_INTEGER*)&c_beg);
iThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)startThread, (LPVOID*)&c_beg, 0, NULL);
WaitForSingleObject(iThread, INFINITE);
}
cout << "suspended" << endl;
for (int i = 0; i < 10; i++) {
QueryPerformanceCounter((LARGE_INTEGER*)&c_beg);
sThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)startThread, (LPVOID*)&c_beg, CREATE_SUSPENDED, NULL);
ResumeThread(sThread);
WaitForSingleObject(sThread, INFINITE);
}
CloseHandle(iThread);
CloseHandle(sThread);
return 0;
}

Making a countdown timer in C++

I have a console application that is intended to only run on windows. It is written in C++. Is there any way to wait 60 seconds (and show remaining time on screen) and then continue code flow?
I've tried different solutions from the internet, but none of them worked. Either they don't work, or they don't display the time correctly.
//Please note that this is Windows specific code
#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
int counter = 60; //amount of seconds
Sleep(1000);
while (counter >= 1)
{
cout << "\rTime remaining: " << counter << flush;
Sleep(1000);
counter--;
}
}
You can use sleep() system call to sleep for 60 seconds.
You can follow this link for how to set 60 seconds timer using system call Timer in C++ using system calls.
possible use Waitable Timer Objects with perion set to 1 second for this task. possible implementation
VOID CALLBACK TimerAPCProc(
__in_opt LPVOID /*lpArgToCompletionRoutine*/,
__in DWORD /*dwTimerLowValue*/,
__in DWORD /*dwTimerHighValue*/
)
{
}
void CountDown(ULONG Seconds, COORD dwCursorPosition)
{
if (HANDLE hTimer = CreateWaitableTimer(0, 0, 0))
{
static LARGE_INTEGER DueTime = { (ULONG)-1, -1};//just now
ULONGLONG _t = GetTickCount64() + Seconds*1000, t;
if (SetWaitableTimer(hTimer, &DueTime, 1000, TimerAPCProc, 0, FALSE))
{
HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
do
{
SleepEx(INFINITE, TRUE);
t = GetTickCount64();
if (t >= _t)
{
break;
}
if (SetConsoleCursorPosition(hConsoleOutput, dwCursorPosition))
{
WCHAR sz[8];
WriteConsoleW(hConsoleOutput,
sz, swprintf(sz, L"%02u..", (ULONG)((_t - t)/1000)), 0, 0);
}
} while (TRUE);
}
CloseHandle(hTimer);
}
}
COORD dwCursorPosition = { };
CountDown(60, dwCursorPosition);
this might be of some help, it's not entirely clear what the question is but this is a countdown timer from 10 seconds, you can change the seconds and add minutes as well as hours.
#include <iomanip>
#include <iostream>
using namespace std;
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
int main()
{
for (int sec = 10; sec < 11; sec--)
{
cout << setw(2) << sec;
cout.flush();
sleep(1);
cout << '\r';
if (sec == 0)
{
cout << "boom" << endl;
}
if (sec <1)
break;
}
}
In c++ you can use countdown. please go through with the following logic which will allow you to show remaining time on the screen.
for(int min=m;min>0;min--) //here m is the total minits as per ur requirements
{
for(int sec=59;sec>=;sec--)
{
sleep(1); // here you can assign any value in sleep according to your requirements.
cout<<"\r"<<min<<"\t"<<sec;
}
}
if you need more help on this then please follow the link here
Hope it will work, please let me know that it is working in your case or not? or if you need any help.
Thanks!

using timer and signal instead of sleep c/c++

I am working on multi threaded code, in which thread has to sleep for particular time. I don't want to wast CPU cycles and want to / have to use timers. This is more or less what I want achieve.
My single threaded code seems to be working fine.
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <sys/siginfo.h>
#include <signal.h>
#include <unistd.h>
volatile sig_atomic_t print_flag = false;
void handle_alarm(int sig)
{
print_flag = true;
}
int main(int argc, char *argv[])
{
//struct sigevent event;
signal( SIGALRM, handle_alarm ); // Install handler first,
timer_t timerid;
struct itimerspec timer;
timer_create(CLOCK_REALTIME,NULL,&timerid);
timer.it_value.tv_sec = 1;
timer.it_value.tv_nsec = 0;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_sec = 0;
std::cout << "Setting timer" << std::endl;
timer_settime(timerid,0,&timer,NULL);
pause();
std::cout << "Hello\n" << std::endl;
return EXIT_SUCCESS;
}
But my multi threaded is stuck in execution. My main thread is stuck at waiting for threads and thread1 is stuck at setting timer. Any idea why thread1 is not completing execution?
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <sys/siginfo.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
volatile sig_atomic_t print_flag = false;
void handle_alarm(int sig)
{
print_flag = true;
}
void *mythread(void* time)
{
signal( SIGALRM, handle_alarm ); // Install handler first,
timer_t timerid;
struct itimerspec timer;
timer_create(CLOCK_REALTIME,NULL,&timerid);
timer.it_value.tv_sec = *(int*)time;
timer.it_value.tv_nsec = 0;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_sec = 0;
std::cout << "Setting timer" << std::endl;
timer_settime(timerid,0,&timer,NULL);
pause();
std::cout << "Hello" << *(int*)time << std::endl;
}
int main(int argc, char *argv[])
{
pthread_t thread1, thread2;
std::cout << "Started threads\n" << std::endl;
int temp1 = 10,temp2 = 5;
pthread_create(&thread1, NULL, &mythread,(void*) &temp1);
pthread_create(&thread2, NULL, &mythread,(void*) &temp2);
std::cout << "Waiting for threads\n" << std::endl;
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
std::cout << "Done\n" << std::endl;
return EXIT_SUCCESS;
}
Edit:
I did it by few methods,
by using nanosleep, it just overcomes one problem, busy wait.
using clock_nanosleep, it is similar to nanosleep except it uses relative clock
Using timer_settime (pulse), the thread waits for pulse for given time and finally clocks out
I did it like this
struct sigevent event;
struct itimerspec itime;
timer_t timer_id;
int chid, rcvid;
my_message_t msg;
chid = ChannelCreate(0);
// following code is used to get kick every pulse period time
// which is 20ms
event.sigev_notify = SIGEV_PULSE;
event.sigev_coid = ConnectAttach(ND_LOCAL_NODE, 0,
chid,
_NTO_SIDE_CHANNEL, 0);
event.sigev_priority = getprio(0);
event.sigev_code = _PULSE_CODE_MINAVAIL;
timer_create(CLOCK_REALTIME, &event, &timer_id);
// 20 ms to nano seconds
itime.it_value.tv_sec = 0;
itime.it_value.tv_nsec = 20000000;
itime.it_interval.tv_sec = 0;
itime.it_interval.tv_nsec = 20000000;
timer_settime(timer_id, 0, &itime, NULL);
SERVO1DELAY1.tv_sec = 0;
SERVO1DELAY1.tv_nsec = 100000;
while(1)
{
rcvid = MsgReceive(chid, &msg, sizeof(msg), NULL);
if (rcvid == 0)
{
// make pulse high for appropriate time
out8( data_handle_A, HIGH );
InterruptDisable();
nanospin(&SERVO1DELAY1);
InterruptEnable();
out8( data_handle_A, LOW );
}
}

WinApi Thread (Pointer error)

I have a probelm :( i wanna make a program wich gives a random number :) i don't want use rand() function :) i wanna make one for me then turn it to a function ;) for educational purpose :)
but i have a problem :( see my code :)
#include <stdio.h>
#include <iostream>
#include <conio.h>
#include <windows.h>
#define MIN 0
#define MAX 99999
using namespace std;
typedef struct _RANDOM_INFO{
DWORD random;
DWORD min;
DWORD max;
} RANDOM_INFO, * LPRANDOM_INFO;
void Error(LPSTR lpErrorMessage){
cout << lpErrorMessage << endl;
exit(EXIT_FAILURE);
}
void GetRandom(LPVOID lpParam){
DWORD dwListSize = 10000, min = 0, max = 99999;
LPDWORD lpRandom = (LPDWORD)lpParam;
LPSTR lpFileSelf, lpKernel, lpNtdll;
HMODULE hFileSelf = NULL, hKernel = NULL, hNtdll = NULL;
hFileSelf = (HMODULE) GetModuleHandle(NULL);
hKernel = (HMODULE) GetModuleHandle("kernel.dll");
hNtdll = (HMODULE) GetModuleHandle("ntdll.dll");
lpFileSelf = (LPSTR) hFileSelf;
lpKernel = (LPSTR) hKernel;
lpNtdll = (LPSTR) hNtdll;
while(1){
DWORD i;
for(i = 0; i <= dwListSize; i++){
*lpRandom = (DWORD)lpFileSelf[i];
}
i = 0;
}
return;
}
int main(int argc, char **argv)
{
DWORD random = 0;
DWORD getRandomThreadId = 0;
HANDLE hGetRandomThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)GetRandom, &random, 0, &getRandomThreadId);
if(hGetRandomThread == INVALID_HANDLE_VALUE)
Error("Cannot make a random list.");
getch();
cout << random << endl;
Sleep(1500);
return 0;
}
The variable should get a value when and print it but i always i get 0 and a windows error can someone tell me why??? and another problem when i try to use the variable hKernel in the GetRandom function i get an error too :( but it works fine whith hFileSelf and hNtdll !!!! is kernel protected from reading???
Note : this is not a random number generation :) its just a way to get a number from the memory when the user click on the enter on his keyboard :), and its not always the same time for all users so its not always the same pointer in memory :) i hope u understand what i want do :) sorry for my bad englush :) just help me to fix the problem :)
Thank u :)
Your GetRandom() function does not have the correct signature for a CreateThread() callback procedure. Try this instead:
#include <stdio.h>
#include <iostream>
#include <conio.h>
#include <windows.h>
#define MIN 0
#define MAX 99999
using namespace std;
typedef struct _RANDOM_INFO
{
DWORD random;
DWORD min;
DWORD max;
} RANDOM_INFO, * LPRANDOM_INFO;
void Error(LPSTR lpErrorMessage)
{
cout << lpErrorMessage << endl;
exit(EXIT_FAILURE);
}
HMODULE hFileSelf = (HMODULE) GetModuleHandle(NULL);
DWORD WINAPI GetRandomThreadProc(LPVOID lpParam)
{
LPDWORD lpRandom = (LPDWORD) lpParam;
DWORD dwListSize = 10000, min = 0, max = 99999;
LPBYTE lpFileSelf = (LPBYTE) hFileSelf;
while (1)
{
for (DWORD i = 0; i <= dwListSize; ++i)
{
*lpRandom = (DWORD) lpFileSelf[i];
}
Sleep(0);
}
return 0;
}
int main(int argc, char **argv)
{
DWORD dwRandom = 0;
DWORD dwRandomThreadId = 0;
HANDLE hGetRandomThread = CreateThread(NULL, 0, &GetRandomThreadProc, &dwRandom, 0, &dwRandomThreadId);
if (hGetRandomThread == INVALID_HANDLE_VALUE)
Error("Cannot make a random list.");
do
{
getch();
cout << dwRandom << endl;
}
while (WaitForSingleObject(hGetRandomThread, 0) == WAIT_TIMEOUT);
CloseHandle(hGetRandomThread);
return 0;
}
i wanna make a program wich gives a random number
What you are doing has nothing to do with random number generation.
This is one way to do it:
Linear Congruential Generator

C++ compiled code using 100% CPU

I have the following code (it gets all processes then search for a regex pattern in them, code for a larger personal project for malware detection), the code does what I want but the only problem it is using 100% of CPU, what do I do wrong? Bad memory allocation? I compiled it with MS Visual Studio 2010 (cl.exe /EHsc mycode.cpp)
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <tlhelp32.h>
#include <psapi.h>
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <iterator>
#include <regex>
using namespace std;
#pragma comment(lib, "psapi.lib")
void PrintProcessNameAndID(DWORD);
void find_locs(HANDLE process);
void ListProcesses();
int main(int argc, char **argv) {
ListProcesses();
}
void find_locs(HANDLE process) {
unsigned char *p = NULL;
MEMORY_BASIC_INFORMATION info;
for ( p = NULL;
VirtualQueryEx(process, p, &info, sizeof(info)) == sizeof(info);
p += info.RegionSize )
{
std::string buffer;
if (info.State == MEM_COMMIT &&
(info.Type == MEM_MAPPED || info.Type == MEM_PRIVATE))
{
DWORD bytes_read;
buffer.resize(info.RegionSize);
ReadProcessMemory(process, p, &buffer[0], info.RegionSize, &bytes_read);
buffer.resize(bytes_read);
const std::tr1::regex rx("([\\w-+]+(?:\\.[\\w-+]+)*#(?:[\\w-]+\\.)+[a-zA-Z]{2,7})");
std::tr1::match_results<std::string::const_iterator> res;
std::tr1::regex_search(buffer, res, rx);
ofstream myfile;
myfile.open ("proc.txt", ios::app);
for (unsigned int i=0; i<res.size(); ++i)
{
std::cout << res[i] << std::endl;
myfile << res[i] << "\n";
}
myfile.close();
}
}
}
void ListProcesses()
{
DWORD aProcesses[1024];
DWORD cbNeeded;
DWORD cProcesses;
unsigned int i;
if (!EnumProcesses(aProcesses,sizeof(aProcesses),&cbNeeded))
return;
cProcesses = cbNeeded / sizeof(DWORD);
for ( i = 0; i < cProcesses; i++ )
{
PrintProcessNameAndID(aProcesses[i]);
}
}
void PrintProcessNameAndID(DWORD processID)
{
TCHAR szProcessName[MAX_PATH]; // = TEXT("<unknown>");
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
if (NULL != hProcess)
{
HMODULE hMod;
DWORD cbNeeded;
if (EnumProcessModules(hProcess, &hMod, sizeof(hMod),
&cbNeeded))
{
GetModuleBaseName(hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR));
}
}
_tprintf(TEXT("pid: %u file: %s\n"), processID, szProcessName);
find_locs(hProcess);
CloseHandle(hProcess);
}
Thanks for help!
There's nothing wrong with a program taking up 100% of the processor... (I don't know how I can expand this answer beyond this)
Any program running continuosly without a Sleep call (some sort of saying to OS "I'm done for now") will try to run as fast as possible, requesting next iteration of the loop just after the previous one. It takes every available CPU cycle, because you've requested it to do so.
A couple things:
The CPU running at 100% is not too uncommon. This is especially true if you are running computationally intensive tasks (such as prime number computations). Eg:
How to get 100% CPU usage from a C program
Or, what is probably more applicable in your case, is that it's due to a myriad combination of things related to windows itself, your hardware combination and configuration:
http://www.techradar.com/us/news/computing/why-is-my-cpu-running-at-100-710254
In all, it's not something to be too worried about. Generally, that is.