Windows via C/C++:线程的执行时间
计算线程执行某项任务消耗的时间时,许多开发人员会调用GetTickCount/GetTickCount64编写如下的代码:
// Get the current time (start time)
ULONGLONG qwStartTime = GetTickCount64();
// Perform complex algorithm here
// Subtract start time from current time to get duration
ULONGLONG dwElapsedTime = GetTickCount64() - qwStartTime;
这段代码假设当前线程不会被中断。然而在Windows这样的基于优先级的操作系统中,开发人员无法得知线程被调度的准确时间。当线程在执行任务中被中断时,使用上面的方法根本无法获得线程所消耗的时间。我们需要一个可以返回线程消耗的CPU时间(既被调度时间)的函数,幸运的是,在Vista之前的操作系统已经提供了GetThreadTimes做到这一点:
BOOL GetThreadTimes(HANDLE hThread,
PFILETIME pftCreationTime,
PFILETIME pftExitTime,
PFILETIME pftKernelTime,
PFILETIME pftUserTime);
GetThreadTime函数会将线程相关的时间信息写入为其传递的PFILETIME参数中,各个参数返回值的含义如下表所示:
参数
意义
pftCreationTime
从1601年1月1号凌晨开始到指定线程被创建时的时间,以100纳秒为单位
pftExitTime
从1601年1月1号凌晨开始到指定线程结束所花的时间,以100纳秒为单位,假如线程尚未终止,则该值未定义
pftKernelTime
线程在内核模式下运行所花的时间,以100纳秒为单位
pftUserTime
线程在用户模式下运行所花的时间,以100纳秒为单位
使用GetThreadTimes可以计算线程所消费的CPU时间,比如下面的代码:
__int64 FileTimeToQuadWord(PFILETIME pft) {
return (Int64ShllMod32(ptf->dwHighDateTime, 32) | ptf->dwLowDateTime);
}
void PerformLongOperation() {
FILETIME ftKernelTimeStart, ftKernelTimeEnd;
FILETIME ftUserTiimeStart, ftUserTimeEnd;
FILETIME ftDummy;
__int64 qwKernelTimeElapsed, qwUserTimeElapsed, qwTotalTimeElapsed;
// Get starting times
GetThreadTimes(GetCurrentThread(), &ftDummy, &ftDummy, &ftKernelTimeStart, &ftUserTimeStart);
// Perform complex algorithm here
...
// Get the ending times
GetThreadTimes(GetCurrentThread(), &ftDummy, &ftDummy, &ftKernelTimeEnd, &ftUserTimeEnd);
// Get the elapsed kernel and user times by c
相关文档:
这篇文章是使用SQLite C/C++接口的一个概要介绍和入门指南。
由于早期的SQLite只支持5个C/C++接口,因而非常容易学习和使用,但是随着SQLite功能的增强,新的C/C++接口不断的增加进来,到现在有超过150个不同的API接口。这往往使初学者望而却步。幸运的是,大多数SQLite中的C/C++接口是专用的,因而很少被使用到。尽管有这 ......
Delphi 与 C/C++ 数据类型对照表
Delphi数据类型C/C++
ShorInt
8位有符号整数
char
Byte
8位无符号整数
BYTE,unsigned short
SmallInt
16位有符号整数
short
Word
16位无符号整数
unsigned short
Integer,LongInt
32位有符号整数
int,long
Cardinal,LongWord/DWORD
32位无符号整数
unsigned long
Int6 ......
排序算法是一种基本并且常用的算法。由于实际工作中处理的数量巨大,所以排序算法对算法本身的速度要求很高。
而一般我们所谓的算法的性能主要是指算法的复杂度,一般用O方法来表示。在后面我将给出详细的说明。
对于排序的算法我想先做一点简单的介绍,也是给这篇文章理一个提纲 ......
函数 - 声明、定义、调用
1. 如果函数没有声明, 应该在调用前定义:
#include <stdio.h>
/* 定义求大值函数 */
int MAX(int x, int y) {
if (x > y)
return x;
else
return y;
}
/* 定义求小值函数 */
int MIN(int x, int y) {
return x &l ......
/加了下面两个头文件,是为了在Win32工程中使用MFC的特性!
#include <afx.h>
#include <afxwin.h>
#include "stdio.h"
#include "conio.h"
////加了下面两句,是为了能够用string(basic_string类型)
#include <string>
using namespace std;
int main(int argc, char* argv[ ......